How to rotate only a specific object without affecting the others in opengl?

1.4k views Asked by At

I'm making a fan in OpenGL, and I have in it the pole and the things that rotate, when I try to rotate them, all the fan rotate with the pole, how im supposed to fix it, I used glutPostRedisplay(), also when I use push and pup matrix in rotation, it doesn't rotate at all, it rotate only once with the angle I have written, any advices help??

2

There are 2 answers

1
Rabbid76 On BEST ANSWER

I use push and pup matrix in rotation, it doesnt rotate at all, it rotate only once

I f you use glPushMatrix / glPopMatrix, then the current matrix is stored on the matrix stack by glPushMatrix and restored when glPopMatrix is called. All matrix transformations which are applied in between are lost.

To achieve a continuously rotation, you've to use an increasing rotation angle. Create a global variable angle and increment it. e.g:

float angle = 0.0f;

void draw()
{
    // ...

    glPushMatrix();

    // apply rotation and increase angle
    glRotatef(angle, 1.0f, 0.0f, 0.0f);
    angle += 1.0f;

    // draw the object
    // ...

    glPopMatrix();

    // ...
}
0
robthebloke On

In the old school opengl, you'd encapsulate the transformation changes between a pair of glPushMatrix (store state of matrix stack) and glPopMatrix (restore previous transform) calls.

glPushMatrix();
  glRotatef(45.0f, 0, 1, 0); //< or whatever your rotation is. 
  drawObjectToBeRotated();
glPopMatrix();

// now any objects drawn here will not be affected by the rotation. 

In modern OpenGL, you'd upload a separate ModelViewProjection matrix as a vertex shader uniform, for each mesh being drawn (and there are a few ways to do this, either in a Uniform variable, Uniform-Buffer-Object, Shader-Storage-Buffer, or some instanced buffer input).