OSG QT :获取鼠标的world坐标

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

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的向量是行向量所以是左乘

猜你喜欢

转载自www.cnblogs.com/bingbingzhe/p/12185372.html
今日推荐