View Full Version : Make object face point

11-23-2012, 11:18 PM
I am trying to place an object in the space, facing an specific direction with an specific rotation.

I know it's position in the world, it's forward vector and it's up vector, but nothing I try works.

I tried calculating pitch and yaw and rotating it using:

double pitch = asin(forward.y/sqrt(forward.x*forward.x + forward.z*forward.z)) * (180/M_PI);
double yaw = atan2(forward.x,forward.z) * (180/M_PI);


but it didn't work. I also tried using gluLookAt


but it didn't work too. I also tried lots of variations.

What is the correct way to do it? I am sure that the forward and up vectors are correct, since I show them on the screen. I am just drawing a line from [0,0,0] to [1,0,0] to test it.

Thanks. =D

11-24-2012, 12:18 AM
You need to translate the object to the origin, apply the rotation and then translate it back to its position. Also remember an object has a facing to start with so your rotation will be
relative to that facing.

11-24-2012, 12:25 AM
I know that it should be in the origin before rotating it. I also didn't aply any transformation before it.

My only problem is what commands should I call to make it face the direction I want it to.

11-24-2012, 04:48 AM
This is some code I did ages ago - I think it works. It uses the OpenGL glm library but the functions are obvious except maybe glm::mat4(1) which makes an identity matrix.
glm is open source so you can look at the code.

Basically it finds a vector perpendicular to the vectors of your current facing and new facing and the angle of rotation and rotates around that axis

glm::vec3 from_vector;
glm::vec3 to_vector;
float cosa = glm::dot(from_vector,to_vector);
glm::vec3 axis = glm::cross(from_vector,to_vector);
float angle = glm::degrees(glm::acos(cosa));
glm::mat4 rotate_matrix = glm::rotate(glm::mat4(1),angle,axis);

11-24-2012, 03:30 PM
Thanks for the code.

I managed to solve my problem. =D