Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

glRotatef not working properly

I am a beginner in openGl. I am doing very basic thing. Just want to rotate an object about x-axis by 20.0 degrees. But instead of rotating it moves upside.

Can anyone help me where i am doing wrong.

Below is my code,

void drawScene(){

    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();

    glColor3f(1.0f, 0.0f, 0.0f);
    glPushMatrix();
    //glTranslatef(1.0f,0.0f,0.0f);
    glRotatef(20.0f,1.0f,0.0f,0.0f);

    glBegin(GL_QUADS);
    glVertex3f(-0.7f, -0.5f, -5.0f);
    glVertex3f(0.7f, -0.5f, -5.0f);
    glVertex3f(0.4f, 0.5f, -5.0f);
    glVertex3f(-0.4f, 0.5f, -5.0f);
    glEnd();
    glPopMatrix();

        glutSwapBuffers();
    }
like image 217
Abdul Samad Avatar asked Dec 16 '22 13:12

Abdul Samad


1 Answers

Rotations always happen relative to the coordinate system of the vertices that it receives. Your object seems to be a plane that is at -5.0 on the Z axis. A rotation matrix rotates around the origin (0, 0, 0) of the coordinate system. Since your object is not centered at the origin, it will rotate around the origin.

The typical way to handle this is to translate the object to the origin, do the rotation, then translate it back. In your case, that would look like:

glTranslatef(0.0f, 0.0f, -5.0f); //Translate back to the original location.
glRotatef(...);                  //Rotate.
glTranslatef(0.0f, 0.0, 5.0f);   //Translate to the origin

Note that you should always read successive transformation operations from bottom to top.

Update

It should be noted that the above solution is more of a stop-gap. The typical way this is done is that models are built centered around the origin. This coordinate system is typically called "model space".

You rotate the points in model space, then translate them into the position in the world where you want them. The only reason we had to move it to the origin in the above code was because the model was not built in model space, so we had to move it to model space.

like image 106
Nicol Bolas Avatar answered Dec 25 '22 19:12

Nicol Bolas