将 2d 屏幕位置投影到 3d 世界空间
我正在使用 glm 数学库来解决以下问题:将 2d 屏幕位置转换为 3d 世界空间。
为了找出问题所在,我将代码简化为以下内容:
float screenW = 800.0f;
float screenH = 600.0f;
glm::vec4 viewport = glm::vec4(0.0f, 0.0f, screenW, screenH);
glm::mat4 tmpView(1.0f);
glm::mat4 tmpProj = glm::perspective( 90.0f, screenW/screenH, 0.1f, 100000.0f);
glm::vec3 screenPos = glm::vec3(0.0f, 0.0f, 1.0f);
glm::vec3 worldPos = glm::unProject(screenPos, tmpView, tmpProj, viewport);
现在,在本例中使用 glm::unProject,我期望 worldPos 为 (0, 0, 1)。然而,它的结果是(127100.12,-95325.094,-95325.094)。
我是否误解了 glm::unProject 应该做什么?我已经跟踪了该函数,它似乎工作正常。
I am using glm maths library for the following problem: converting a 2d screen position into 3d world space.
In an attempt to track down the problem, I have simplified the code to the following:
float screenW = 800.0f;
float screenH = 600.0f;
glm::vec4 viewport = glm::vec4(0.0f, 0.0f, screenW, screenH);
glm::mat4 tmpView(1.0f);
glm::mat4 tmpProj = glm::perspective( 90.0f, screenW/screenH, 0.1f, 100000.0f);
glm::vec3 screenPos = glm::vec3(0.0f, 0.0f, 1.0f);
glm::vec3 worldPos = glm::unProject(screenPos, tmpView, tmpProj, viewport);
Now with the glm::unProject in this case I would expect worldPos to be (0, 0, 1). However it is coming through as (127100.12, -95325.094, -95325.094).
Am I misunderstanding what glm::unProject is supposed to do? I have traced through the function and it seems to be working OK.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
screenPos 中的 Z 分量对应于深度缓冲区中的值。所以 0.0f 是近裁剪平面,1.0f 是远裁剪平面。
如果你想找到距离屏幕一个单位的世界位置,你可以重新调整向量:
还要注意,screenPos 0,0 指定屏幕的左下角,而在 worldPos 中 0,0 是中心屏幕的。所以 0,0,1 应该给你 -1.3333,-1,-1,400,300,1 应该给你 0,0,-1。
The Z component in screenPos corresponds to the values in the depth buffer. So 0.0f is the near clip plane and 1.0f is the far clip plane.
If you want to find the world pos that is one unit away from the screen, you can rescale the vector:
Note also that the screenPos of 0,0 designates the bottom left corner of the screen, while in worldPos 0,0 is the center of the screen. So 0,0,1 should give you -1.3333,-1,-1, and 400,300,1 should give you 0,0,-1.