ManIkWeet
ManIkWeet

Reputation: 1338

Rotate object to "look at" another object in 3 dimensions?

I want to create a formula that rotates my object (o1) to always point into the direction of another object (o2), regardless of o1's position.

Kind of like the camera in the following image: http://puu.sh/bLUWw/aaa653accf.png

I got the following code so far, but the yaw-axis seems to be inverted:

Vector3 lookat = { lookAtPosition.x, lookAtPosition.y, lookAtPosition.z };
Vector3 pos = { position.x, position.y, position.z };
Vector3 objectUpVector = { 0.0f, 1.0f, 0.0f };

Vector3 zaxis = Vector3::normalize(lookat - pos);
Vector3 xaxis = Vector3::normalize(Vector3::cross(objectUpVector, zaxis));
Vector3 yaxis = Vector3::cross(zaxis, xaxis);

Matrix16 pm = {
    xaxis.x, yaxis.x, zaxis.x, 0,
    xaxis.y, yaxis.y, zaxis.y, 0,
    xaxis.z, yaxis.z, zaxis.z, 0,
    0, 0, 0, 1
};

See the following image: http://puu.sh/bLUSG/5228bb2176.jpg

I'm sure it's just a few variables that have to be swapped, but I couldn't find them...

PS: The position of the object matrix is multiplied at a later stage, for testing purposes...

Upvotes: 3

Views: 4165

Answers (2)

ManIkWeet
ManIkWeet

Reputation: 1338

I found the answer to my issue, it turns out that I just had to change the order of the values inside the matrix like so:

Matrix16 pm = {
    xaxis.x, xaxis.y, xaxis.z, 0,
    yaxis.x, yaxis.y, yaxis.z, 0,
    zaxis.x, zaxis.y, zaxis.z, 0,
    0, 0, 0, 1
};

Upvotes: 2

Spektre
Spektre

Reputation: 51863

camera matrix is inverse of transform matrix representing its coordinate system

  • look here: Transform matrix anatomy
  • origin = o1.position
  • Z axis = o1.position-o2.position
    • and make it unit length of coarse
    • mine frustrum/Zbuffer are configured to view in -Z axis direction
  • now just compute X,Y axises as perpendicular to eachother and Z also via crossproduct
    • and make them unit length of coarse
    • so take some vector (non parallel to Z)
    • ideally something best to align to like Up vector (0,1,0);
    • multiply it by Z axis and store result to X(or Y)
    • and then multiply it again by Z axis and store to Y(or X).
  • Now you have the transform matrix M1 representing O1 coordinate system
  • if you want just to render the object then thi is it
  • if you want to have camera on object o1
  • then just compute:
  • ViewMatrix=inverse(M1)*ProjectionMatrix;
  • here inverse matrix computation for mine OpenGL matrices

Upvotes: 1

Related Questions