Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to rotate model not camera in OpenGL?

I have the same qustion as in the title :/ I make something like:

  glMatrixMode(GL_MODELVIEW);
  glLoadIdentity();
  glTranslatef(0.0f, 0, -zoom);
  glRotatef(yr*20+moveYr*20, 0.0f, 1.0f, 0.0f);
  glRotatef(zr*20+moveZr*20, 1.0f, 0.0f, 0.0f);

  //Here model render :/

And in my app camera is rotating not model :/

like image 851
openglNewbie Avatar asked Oct 26 '10 13:10

openglNewbie


1 Answers

Presumably the reason you believe it's your camera moving and not your model is because all the objects in the scene are moving together?

After rendering your model and before rendering other objects, are you resetting the MODELVIEW matrix? In other words, are you doing another glLoadIdentity() or glPopMatrix() after you render the model you're talking about and before rendering other objects?

Because if not, whatever transformations you applied to that model will also apply to other objects rendered, and it will be as if you rotated the whole world (or the camera).

I think there may be another problem with your code though:

  glTranslatef(0.0f, 0, -zoom);
  glRotatef(yr*20+moveYr*20, 0.0f, 1.0f, 0.0f);
  glRotatef(zr*20+moveZr*20, 1.0f, 0.0f, 0.0f);
  //Here model render :/

Are you trying to rotate your model around the point (0, 0, -zoom)?

Normally, in order to rotate around a certain point (x,y,z), you do:

  1. Translate (x,y,z) to the origin (0,0,0) by translating by the vector (-x,-y,-z)
  2. Perform rotations
  3. Translate the origin back to (x,y,z) by translating by the vector (x,y,z)
  4. Draw

If you are trying to rotate around the point (0,0,zoom), you are missing step 3. So try adding this before you render your model:

glTranslatef(0.0f, 0, zoom); // translate back from origin

On the other hand if you are trying to rotate the model around the origin (0,0,0), and also move it along the z-axis, then you will want your translation to come after your rotation, as @nonVirtual said.

And don't forget to reset the MODELVIEW matrix before you draw other objects. So the whole sequence would be something like:

  glMatrixMode(GL_MODELVIEW);
  glLoadIdentity();

#if you want to rotate around (0, 0, -zoom):
  glTranslatef(0.0f, 0, -zoom);
  glRotatef(yr*20+moveYr*20, 0.0f, 1.0f, 0.0f);
  glRotatef(zr*20+moveZr*20, 1.0f, 0.0f, 0.0f);
  glTranslatef(0.0f, 0, zoom); // translate back from origin
#else if you want to rotate around (0, 0, 0):
  glRotatef(yr*20+moveYr*20, 0.0f, 1.0f, 0.0f);
  glRotatef(zr*20+moveZr*20, 1.0f, 0.0f, 0.0f);
  glTranslatef(0.0f, 0, -zoom);
#endif    
  //Here model render :/

  glLoadIdentity();
  // translate/rotate for other objects if necessary
  // draw other objects
like image 101
LarsH Avatar answered Sep 23 '22 01:09

LarsH