3D 屏幕空间光线投射/拾取 DirectX9 [英] 3D Screenspace Raycasting/Picking DirectX9
问题描述
我需要根据特定深度(用于光线投射)将 2D 鼠标坐标转换为 3D 世界坐标.我没有直接在 C++ 中使用 DirectX,我使用的是专有语言,但如果你用 C++ 或伪代码(首选 C++)给我答案,我可以转换它.
I need to convert a 2D mouse coordinate to a 3D world coordinate based on a specific depth (it's for raycasting). I'm not directly using DirectX in C++, I'm using a proprietary language, but if you give me an answer in C++ or pseudocode (C++ preferred) I can convert it.
我可以访问世界矩阵、视图矩阵和投影矩阵以及各种矩阵操作功能.
I have access to the world matrix, view matrix and projection matrix and a variety of matrix manipulation functions.
如果需要将 vector4 乘以 matrix4,我唯一可以使用 vector4 和 matrix4 的函数是 transformVector4(vector4Source,matrix4Source)
.如果这很重要,我不确定它以哪个顺序乘以它们.
If it's necessary to multiply a vector4 by a matrix4, the only function I have available that takes both a vector4 and a matrix4 is transformVector4(vector4Source,matrix4Source)
. I'm not sure which order it multiplies them in, if that matters.
任何帮助将不胜感激:) 我已经为此工作了几个小时,但我只是没有获得 3D 数学...
Any help would be much appreciated :) I've been working on this for hours and I just don't get 3D maths...
推荐答案
要将鼠标转换为光线,请执行以下过程:
To convert you mouse to ray, you do this process:
将鼠标坐标从像素坐标转换为 -1/1 坐标(-1,-1 为左下角).
Convert your mouse coordinates from pixel coordinate to -1/1 coordinates (-1,-1 being bottom left).
射线原点为(近平面矢量)
ray origin will be (vector at near plane)
vector3 origin = vector3(mousex,mousey,0);
射线端是(远平面的向量)
ray end is (vector at far plane)
vector3 far = vector3(mousex,mousey,1);
现在你需要对这些向量应用变换,首先你需要为它创建变换矩阵:
now you need to apply transform to those vectors, first you need to create transformation matrix for it:
matrix4x4 inverseviewproj = invertmatrix(view * proj)
将此转换应用于两个向量:
Apply this transformation to both vectors:
vector3 rayorigin = transform(origin, inverseviewproj);
vector3 rayend = transform(far, inverseviewproj);
你的射线方向是:
vector3 raydirection = normalize(rayend-rayorigin);
就是这样,现在您可以使用光线投射功能了.
That's about it, now you can use raycast functions.
如果您只能访问 vector4 以通过矩阵转换向量,w 分量需要为 1,例如:
In case you only have access to vector4 to transform vector by a matrix, the w component needs to be 1 in eg:
vector4 origin = vector3(mousex,mousey,0,1);
vector4 far = vector3(mousex,mousey,1,1);
要提取方向,请确保首先将 vector4 转换为 vector3(否则会影响归一化).
to extract direction make sure to first convert your vector4 into vector3 (since it will affect normalization otherwise).
这篇关于3D 屏幕空间光线投射/拾取 DirectX9的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!