简体   繁体   English

OpenGL4 - 如何旋转 object 以查看另一个 object

[英]OpenGL4 - How to rotate object to look at another object

I am trying to make one object rotate to look at another object.我正在尝试让一个 object 旋转以查看另一个 object。 I can't seem to find a working solution, though.不过,我似乎找不到可行的解决方案。 Does anyone know how to do this?有谁知道如何做到这一点? I have tried:我努力了:

   public static Matrix4 LookAt(Vector3 eye, Vector3 target, Vector3 up)
        {
            Vector3 z = (eye - target).Normalize();
            Vector3 x = Vector3.Cross(up, z).Normalize();
            Vector3 y = Vector3.Cross(z, x).Normalize();

            Matrix4 matrix = new Matrix4(new Vector4(x.X, y.X, z.X, 0.0f),
                                        new Vector4(x.Y, y.Y, z.Y, 0.0f),
                                        new Vector4(x.Z, y.Z, z.Z, 0.0f),
                                        Vector4.UnitW);

            return Matrix4.CreateTranslation(-eye) * matrix;
        }

but it did not work. 但它没有用。

The code seems fine for generating a LookAt matrix in a RH coordinate system.该代码似乎可以在 RH 坐标系中生成 LookAt 矩阵。

Given you say that it works for cameras but not for objects, it suggests that you're using the wrong coordinate space somewhere along the line.鉴于您说它适用于相机但不适用于物体,这表明您沿线某处使用了错误的坐标空间。 The LookAt matrix transforms vertices in world space into the coordinate system of the camera, what you are trying to do is use this matrix to transform local object vertices of your mesh, which presumably points down the local -Z axis, into world space. LookAt 矩阵将世界空间中的顶点转换为相机的坐标系,您要做的是使用此矩阵将网格的局部 object 顶点(可能指向局部 -Z 轴)转换为世界空间。 So you need to invert the LookAt matrix if you're using it in this way?所以如果你以这种方式使用它,你需要反转 LookAt 矩阵吗?

I found the solution in an article on a Blogspot page .我在Blogspot 页面上的一篇文章中找到了解决方案。

public void LookAt(Vector3 Position, Vector3 target, Vector3 Up)
    {
        Vector3 delta = target - Position;
        Vector3 direction = Vector3.Normalize(delta);
        Vector3 up = Up.Normalize();
        Vector3 right = Vector3.Cross(up, direction).Normalize();
        up = Vector3.Cross(direction, right).Normalize();

        RotationMatrix = new Matrix4(
            new Vector4(right.X, right.Y, right.Z, 0.0f),
            new Vector4(up.X, up.Y, up.Z, 0.0f),
            new Vector4(direction.X, direction.Y, direction.Z, 0.0f),
            new Vector4(Position.X, Position.Y, Position.Z, 1.0f));
    }

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

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