欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

osg鼠标点选类

程序员文章站 2022-06-10 21:01:07
...

 

添加了注释便于理解


class mousehandle:public osgGA::GUIEventHandler
{
public:
	mousehandle(){}
	~mousehandle(){}
	void pick(osgViewer::View* view,float x,float y);
	bool handle(const osgGA::GUIEventAdapter& ea,osgGA::GUIActionAdapter& aa);//ea,鼠标点击位置   //aa 控制显示参数,是Viewer的祖父类,由它可以得到viewer
protected:
	float _mx;
	float _my;
};
bool mousehandle::handle(const osgGA::GUIEventAdapter& ea,osgGA::GUIActionAdapter& aa)
{
	osgViewer::View* view = dynamic_cast<osgViewer::View*>(&aa);
	if (!view) return false;

	switch(ea.getEventType())
	{
		//鼠标按下
	case(osgGA::GUIEventAdapter::PUSH):
		{
			if (ea.getButton() == osgGA::GUIEventAdapter::LEFT_MOUSE_BUTTON)//鼠标左键
			{
				//更新鼠标位置
				_mx = ea.getX();
				_my = ea.getY();
				//pick(view, ea.getX(), ea.getY());
			}
			break;
		}
		//拖动鼠标
	case(osgGA::GUIEventAdapter::DRAG):
		//释放/抬起鼠标
	case(osgGA::GUIEventAdapter::RELEASE):
		{
			if (_mx==ea.getX() && _my==ea.getY())//判断当前抬起鼠标点位置与鼠标点击位置是否相同,即是否存在拖动鼠标
			{   
				pick(view, ea.getX(), ea.getY());//执行对象选取
			}
			break;
		}
	default:
		break;
	}
	return false;
}
//实现鼠标点选
void mousehandle::pick(osgViewer::View* view, float x, float y)
{
	osg::ref_ptr<osg::Node> node = new osg::Node();
	osg::ref_ptr<osg::Group> parent = new osg::Group();
	node=nullptr;
	parent=nullptr;
	//创建一个线段交集检测//intersections 存放与射线相交的节点
	osgUtil::LineSegmentIntersector::Intersections intersections;
    //computeIntersections()函数判断鼠标与场景中对象交点
	if (view->computeIntersections(x, y, intersections))
	{
		osgUtil::LineSegmentIntersector::Intersections::iterator intersection=intersections.begin();  //获取第一个交点
		const osg::NodePath& nodePath = intersection->nodePath;//获取第一个交点的path	
		//得到选择的物体
		node = (nodePath.size()>=1)?nodePath[nodePath.size()-1]:0;//获取交点所在的子节点
		parent = (nodePath.size()>=2)?dynamic_cast<osg::Group*> 
                         (nodePath[nodePath.size()-2]):0;//获取交点的父节点/组节点
	}
	
	if (parent.get() && node.get())//选中模型
	{
		//添加选中后事件
	}
	
}

 

相关标签: osg