PDA

View Full Version : Make object face point



beastarman
11-24-2012, 12:18 AM
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);

glRotated(pitch,1,0,0);
glRotated(yaw,0,1,0);


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



gluLookAt(
0,0,0,
forward.x,forward.y,forward.z,
up.x,up.y,up.z);


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

tonyo_au
11-24-2012, 01: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.

beastarman
11-24-2012, 01: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.

tonyo_au
11-24-2012, 05: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;
glm::normalize(from_vector);
glm::normalize(to_vector);
float cosa = glm::dot(from_vector,to_vector);
glm::clamp(cosa,-1.0f,1.0f);
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);

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

I managed to solve my problem. =D