我试图在 2D 屏幕空间上用户选择的点的 3D 空间上放置一个球体。为此,我尝试使用以下技术从 2d 点计算 3d 点,但该技术没有给出正确的解决方案。
mousePosition.x = ((clickPos.clientX - window.left) / control.width) * 2 - 1;
mousePosition.y = -((clickPos.clientY - window.top) / control.height) * 2 + 1;
然后我将mousePosition
与MVP矩阵的逆矩阵
相乘。但在结果中得到随机数。
用于计算 MVP 矩阵:
osg::Matrix mvp = _camera->getViewMatrix() * _camera->getProjectionMatrix();
我该如何继续?谢谢。
最佳答案
假设鼠标位置在 x 和 y 的范围 [-1, 1] 内标准化,以下代码将为您提供从鼠标坐标投影的世界坐标中的 2 个点:nearPoint
是 3D 中位于相机平截头体近平面上的点,farPoint
位于平截头体远平面上。
您可以计算出一条经过这些点并与您的平面相交的线。
// compute the matrix to unproject the mouse coords (in homogeneous space)
osg::Matrix VP = _camera->getViewMatrix() * _camera->getProjectionMatrix();
osg::Matrix inverseVP;
inverseVP.invert(VP);
// compute world near far
osg::Vec3 nearPoint(mousePosition.x, mousePosition.x, -1.0f);
osg::Vec3 farPoint(mousePosition.x, mousePosition.x, 1.0f);
osg::Vec3 nearPointWorld = nearPoint * inverseVP;
osg::Vec3 farPointWorld = farPoint * inverseVP;
关于c++ - 如何在 Openscenegraph 中从 2D 鼠标单击屏幕坐标点计算 3D 点(世界坐标)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51293859/