OSG QT :获取鼠标的world坐标

假装没事ソ 提交于 2020-01-13 00:28:15

网上的代码大部分是这样的:

1         auto matViewMatrix = camera->getViewMatrix();
2         auto matProjectionMatrix = camera->getProjectionMatrix();
3         auto wndMatrix = camera->getViewport()->computeWindowMatrix();
4         osg::Matrix MVPW = matViewMatrix * matProjectionMatrix * wndMatrix;
5         osg::Matrix inverseMVPW = osg::Matrix::inverse(MVPW);
6         osg::Vec3 mouseWorld = osg::Vec3(x,y, 0) * inverseMVPW;

在和QT结合的开发的时候,发现这个位置是错误的,因为是鼠标获取的坐标的原点是左上角,而OSG的世界坐标系的原点是左下角,所以要把鼠标的Y值做转换。

像下面这样的:

 1 void GraphicsWinQt::mouseMoveEvent( QMouseEvent *event )
 2 {
 3     setKeyboardModifiers( event );
 4     this->getEventQueue()->mouseMotion(event->x(), event->y());
 5     if(nullptr != m_pMainWnd)
 6     {
 7         auto x = event->x();
 8         auto y = event->y();
 9         int iWindowHeight = this->height();
10         //坐标值转换
11         y = iWindowHeight - y;
12         int z = 0;
13         osg::Camera* camera = m_pViewer->getCamera();
14 
15         auto matViewMatrix = camera->getViewMatrix();
16         auto matProjectionMatrix = camera->getProjectionMatrix();
17         auto wndMatrix = camera->getViewport()->computeWindowMatrix();
18         osg::Matrix MVPW = matViewMatrix * matProjectionMatrix * wndMatrix;
19         osg::Matrix inverseMVPW = osg::Matrix::inverse(MVPW);
20         osg::Vec3 mouseWorld = osg::Vec3(x,y, 0) * inverseMVPW;
21 
22         auto s = QStringLiteral("当前位置:");
23         s += QString("%1,%2,%3").arg(mouseWorld.x()).arg(mouseWorld.y()).arg(mouseWorld.z());
24         auto pEvent = MessageEvent::CreateInstance(1);
25         pEvent->m_sMsg = s;
26         qApp->postEvent(m_pMainWnd, pEvent);
27     }
28 }

另外OSG的向量是行向量所以是左乘

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!