简体   繁体   English

将屏幕2D转换为世界3D坐标

[英]Converting Screen 2D to World 3D Coordinates

I want to convert 2D screen coordinates to 3D world coordinates. 我想将2D屏幕坐标转换为3D世界坐标。 I have searched a lot but I did not get any satisfying result. 我进行了很多搜索,但没有得到满意的结果。

Note: I am not using OpenGL nor any other graphics library. 注意:我没有使用OpenGL或任何其他图形库。

Data which I have: 我拥有的数据:

Screen X 屏幕X

Screen Y 屏幕Y

Screen Height 屏幕高度

Screen Width 屏幕宽度

Aspect Ratio 长宽比

If you have the Camera world Matrix and Projection Matrix this is pretty simple. 如果您拥有“相机世界”矩阵和“投影矩阵”,这将非常简单。

If you don't have the world Matrix you can compute it from it's position and rotation. 如果您没有世界矩阵,则可以根据其位置和旋转度对其进行计算。

worldMatrix = Translate(x, y, z) * RotateZ(z_angle) * RotateY(y_angle) * RotateX(x_angle);

Where translate returns the the 4x4 translation matrices and Rotate returns the 4x4 rotation matrices around the given axis. 其中平移返回4x4平移矩阵,而Rotate返回围绕给定轴的4x4旋转矩阵。

The projection matrix can be calculated from the aspect ratio, field of view angle, and near and far planes. 投影矩阵可以从纵横比,视场角以及近平面和远平面中计算得出。

This blog has a good explanation of how to calculate the projection matrix. 该博客很好地解释了如何计算投影矩阵。

You can unproject the screen coordinates by doing: 您可以通过以下操作取消投影屏幕坐标:

mat = worldMatrix * inverse(ProjectionMatrix)
dir = transpose(mat) * <x_screen, y_screen, 0.5, 1>

dir /= mat[3] + mat[7] + mat[11] + mat[15]
dir -= camera.position

Your ray will point from the camera in the direction dir. 光线将从相机指向方向dir。

This should work, but it's not a super concreate example on how to do this. 这应该可以工作,但它不是如何执行此操作的超级示例。

Basically you just need to do the following steps: 基本上,您只需要执行以下步骤:

calculate camera's worldMatrix
calculate camera's projection matrix
multiply worldMatrix with inverse projection matrix.

create a point <Screen_X_Value, Screen_Y_Value, SOME_POSITIVE_Z_VALUE, 1>
apply this "inverse" projection to your point.
then subtract the cameras position form this point.

The resulting vector is the direction from the camera. 产生的矢量是相机的方向。 Any point along that ray are the 3D coordinates corresponding to your 2D screen coordinate. 沿该射线的任何点都是与2D屏幕坐标对应的3D坐标。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM