osg鼠标点选类

 

添加了注释便于理解


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())//选中模型
	{
		//添加选中后事件
	}
	
}

 

  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值