简单一个碰撞检测:
一条直线和一个正方体是否有交点:
#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();
}
运行结果:
具体调用过程: