取消项目MouseCoords(OpenGL / OpenTK)。

时间:2017-02-02 02:09:10

标签: c# opengl mouse opentk

嘿我正在尝试将2D鼠标坐标转换为3D方向向量到世界空间。问题是如果摄像机没有在Y轴上转动,光线的方向矢量只能完全工作。例如:相机往下看。 Y是-0.999,这是完美的,但现在我将相机在Y轴上旋转90°,结果是X现在是-0.999而Y非常小(但仍然向下看)。工作的唯一方向是Z。

这是获取鼠标光线的代码。

        public Vector3 get3DMouseCoords(int mousex, int mousey)
    {
        Vector2 normalizedCoords = getNormalizedMouseCoords(mousex, mousey);
        Vector4 clipCoords = new Vector4(normalizedCoords.X, normalizedCoords.Y, -1f, 1f);
        Vector4 eyeRay = getEyeRay(clipCoords);
        return getWorldRay(eyeRay);
    } 

    private Vector3 getWorldRay(Vector4 eyeRay)
    {
        Matrix4 invertertedView = Matrix4.Invert(Camera.Transformation);
        Vector3 worldRay = Vector4.Transform(invertertedView, eyeRay).Xyz;
        return worldRay.Normalized();
    }

    private Vector4 getEyeRay(Vector4 clipCoords)
    {
        Matrix4 invertertedProj = Matrix4.Invert(Camera.PerspectiveProjection);
        Vector4 eyeRay = Vector4.Transform(invertertedProj, clipCoords);
        return new Vector4(eyeRay.X, eyeRay.Y, -1f, 0f);
    }

    private Vector2 getNormalizedMouseCoords(int mousex, int mousey)
    {
        float x = 2.0f * mousex / (float)screenWidth - 1;
        float y = -(2.0f * mousey / (float)screenHeight - 1);
        return new Vector2(x, y);
    }

这是视图矩阵代码:

                    Vector3 lookat = new Vector3();

                lookat.X = (float)(Math.Sin((float)orientation.X) * Math.Cos((float)orientation.Y));
                lookat.Y = (float)Math.Sin((float)orientation.Y);
                lookat.Z = (float)(Math.Cos((float)orientation.X) * Math.Cos((float)orientation.Y));

                view = Matrix4.LookAt(Position, Position + lookat, Vector3.UnitY);

先谢谢。

0 个答案:

没有答案