Luatic
Luatic

Reputation: 11201

Rotate around camera opengl c++ / Set center for rotation

Opengl rotates always around (0,0,0). But I need to rotate around the camera. I know that in GL, there is no camera, but if I translate back to (0,0,-6.0) , it rotates around (0,0,0), not around (0,0,-6.0)

So my question is : How to set the rotation centre in opengl and c++

I already found this post : OpenGL rotating a camera around a point

Where this solution is showed :

rotation functions normally rotate about the origin. To rotate around another point P you have to: translate(-P) rotate translate(P)

And I dont now how to realize the

translate(P)

because after the rotation the translation is relative to the rotation

Example : I want to rotate around (1,1,1). I translate (-1,-1,-1). Now I rotate it around the x-axis by 90 degrees. Its right. But now I have to translate it back. If I translate (1,1,1), it wont work, because its now rotated, and the movement is relative to the rotated matrix.

PS : I dont want to use gluLookAt()

So my code would be :

//set rotation to zero
glRotatef(-yr,0.0f,1.0f,0.0f);  
glRotatef(-xr,1.0f,0.0f,0.0f);
//set points relative to camera
glTranslatef(cam_pos[0],cam_pos[1],cam_pos[2]);
//rotate back
glRotatef(yr,0.0f,1.0f,0.0f);   
glRotatef(xr,1.0f,0.0f,0.0f);
//rotate
glRotatef(angley,0.0f,1.0f,0.0f);   
glRotatef(anglex,1.0f,0.0f,0.0f);
//and now, how to translate back,
//movement is relative to the cam ?
//I would simply use :  
//glTranslatef(-cam_pos[0],-cam_pos[1],-cam_pos[2]);
//which wont work because its relative to the new rotation.

Any help is greatly appreciated !

Upvotes: 0

Views: 936

Answers (1)

Luatic
Luatic

Reputation: 11201

So, I actually figured out that movement isnt relative to rotation, what makes everything easy to realize. Code :

glTranslatef(point_to_rotate_around_x,point_to_rotate_around_y,point_to_rotate_around_z);
glRotatef(anglex,1,0,0);
glRotatef(angley,0,1,0);
glTranslatef(-point_to_rotate_around_x,-point_to_rotate_around_y,-point_to_rotate_around_z);

Thanks @derhass, who told me that its backwards.

Upvotes: 1

Related Questions