简体   繁体   中英

OpenGL4 - How to rotate object to look at another object

I am trying to make one object rotate to look at another 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.

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. So you need to invert the LookAt matrix if you're using it in this way?

I found the solution in an article on a Blogspot page .

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));
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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