osg学习第三篇:碰撞检测(一)


绘制一个正方体:

//画正方体
osg::ref_ptr CreatBox()
{
	osg::ref_ptr gnode = new osg::Geode;
	gnode->addDrawable(new osg::ShapeDrawable(new osg::Box(osg::Vec3(0,0,0),10.0,10.0,10.0)));
	//gnode->addDrawable(new osg::ShapeDrawable(new osg::Box(osg::Vec3(0,0,0),0.1,0.1,20)));
	return gnode;
}

 

绘制线段:

//画线
osg::ref_ptr CreateLine(const osg::Vec3 &start, const osg::Vec3 &end)
{
	osg::ref_ptr gnode = new osg::Geode;
	osg::ref_ptr gy = new osg::Geometry;

	osg::ref_ptr coords = new osg::Vec3Array;

	gnode ->addDrawable(gy);
	gy->setVertexArray(coords);
	coords->push_back(start);
	coords->push_back(end);
	gy->addPrimitiveSet(new osg::DrawArrays(osg::PrimitiveSet::LINE_LOOP,0,2));

	return gnode;
}


绘制小球(线段与正方体的碰撞点用小球标记)

//画球
osg::ref_ptr CreateSphere(osg::Vec3d ¢er)
{
	osg::ref_ptr gnode = new osg::Geode;
	gnode->addDrawable(new osg::ShapeDrawable(new osg::Sphere(center,0.5)));
	return gnode;
}

 

碰撞检测的核心代码

	//碰撞检测核心代码。(线的碰撞)
	osgUtil::LineSegmentIntersector::Intersections intersections;
	osg::ref_ptr ls = new osgUtil::LineSegmentIntersector(start,end);
	osg::ref_ptr iv = new osgUtil::IntersectionVisitor(ls);
	//


输出碰撞的点

//输出所有的交点
	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()<addChild(CreateSphere(iter->getWorldIntersectPoint()));
		}
	}

其中,在碰撞点的地方调用画球的函数,添加到组件中:

group->addChild(CreateSphere(iter->getWorldIntersectPoint()));

 

效果图:
osg学习第三篇:碰撞检测(一)_第1张图片


 

你可能感兴趣的:(osg学习第三篇:碰撞检测(一))