OSG碰撞检测

版权声明:本文为博主原创文章,未经同意不允许转载! https://blog.csdn.net/wb175208/article/details/80623788

简单一个碰撞检测:
一条直线和一个正方体是否有交点:

#include "../Common.h"

osg::ref_ptr<osg::Geode> createGeode();

int main() {

    osg::ref_ptr<osgViewer::Viewer> viewer = new osgViewer::Viewer;
    viewer->addEventHandler(new osgViewer::WindowSizeHandler);
    viewer->addEventHandler(new osgViewer::StatsHandler);

    osg::ref_ptr<osg::Group> root = new osg::Group;
    osg::ref_ptr<osg::Node> node = osgDB::readNodeFile("xyz.osgt");
    //root->addChild(node.get());

    osg::Vec3* start = new osg::Vec3(0.0, 0.0, 15.0);
    osg::Vec3* end = new osg::Vec3(0.0, 0.0, -15.0);
    osg::ref_ptr<osgUtil::LineSegmentIntersector> ls = new osgUtil::LineSegmentIntersector(*start, *end);
    osg::ref_ptr<osgUtil::IntersectionVisitor> iv = new osgUtil::IntersectionVisitor(ls);

    root->addChild(createGeode());

    root->accept(*iv.get());

    osgUtil::LineSegmentIntersector::Intersections intersections;
    if (ls->containsIntersections()){
        intersections = ls->getIntersections();
        for (osgUtil::LineSegmentIntersector::Intersections::iterator iter = intersections.begin(); iter != intersections.end(); iter++) {
            std::cout << iter->getWorldIntersectPoint().x() << ":" << iter->getWorldIntersectPoint().y() << ":" << iter->getWorldIntersectPoint().z() << std::endl;
        }
    } else {
        std::cout << "no !";
    }

    viewer->setSceneData(root.get());
    return viewer->run();
}

osg::ref_ptr<osg::Geode> createGeode() {
    osg::ref_ptr<osg::Geode> geode = new osg::Geode;


    osg::ref_ptr<osg::TessellationHints> hits = new osg::TessellationHints;
    hits->setDetailRatio(0.5);

    osg::ref_ptr<osg::Box> box = new osg::Box(osg::Vec3(0.0, 0.0, 0.0), 1.0);
    osg::ref_ptr<osg::ShapeDrawable> shape = new osg::ShapeDrawable(box, hits);
    geode->addDrawable(shape);


    return geode.get();
}

运行结果:
这里写图片描述

具体调用过程:
这里写图片描述

猜你喜欢

转载自blog.csdn.net/wb175208/article/details/80623788