如何获取二维点,并通过透视相机将其投影到三维矢量中



我有一个2D点(x,y(,我想把它投影到矢量上,这样我就可以执行光线跟踪来检查用户是否点击了3D对象,我已经写了所有其他代码,除了当我回到我的函数从鼠标的xy线获取矢量时,我没有考虑视场,我不想猜测因素是什么,因为"voodoo"修复程序对于库来说不是一个好主意。有数学魔术师想帮忙吗?:-(。

这是我当前的代码,需要应用相机的FOV:

sf::Vector3<float> Camera::Get3DVector(int Posx, int Posy, sf::Vector2<int> ScreenSize){
    //not using a "wide lens", and will maintain the aspect ratio of the viewport
    int window_x = Posx - ScreenSize.x/2;
    int window_y = (ScreenSize.y - Posy) - ScreenSize.y/2;
    float Ray_x = float(window_x)/float(ScreenSize.x/2);
    float Ray_y = float(window_y)/float(ScreenSize.y/2);
    sf::Vector3<float> Vector(Ray_x,Ray_y, -_zNear);
    // to global cords
    return MultiplyByMatrix((Vector/LengthOfVector(Vector)), _XMatrix, _YMatrix, _ZMatrix);
}

你不会太在意,有一点是要确保你的鼠标在-1到1的空间(而不是0到1(然后创建两个矢量:

Vector3 orig = Vector3(mouse.X,mouse.Y,0.0f);
Vector3 far = Vector3(mouse.X,mouse.Y,1.0f);

你还需要使用你的透视变换的逆变换(或者如果你想要世界空间的话,可以使用视图投影(

Matrix ivp = Matrix::Invert(Projection)

然后你做:

Vector3 rayorigin = Vector3::TransformCoordinate(orig,ivp);
Vector3 rayfar = Vector3::TransformCoordinate(far,ivp);

如果你想要一条射线,你还需要方向,简单地说就是:

Vector3 raydir = Normalize(rayfar-rayorigin);

最新更新