Gabriella Alice Karin
Gabriella Alice Karin

Reputation: 31

rotating objects in opengl

I need to rotate the scene in an axis when I press a key. Here's how I implemented it

    int rotateFlag;

    void rotateScene(int x){
         if(x)//rotate 45 deg on x axis
             glRotatef(45,1,0,0);
         else // roatate 45 deg on y axis
             glRotatef(45,0,1,0); 
    }

    //this is the function I call in  glutDisplayFunc
    void drawScene(void){
         glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
         glMatrixMode(GL_MODELVIEW); 
         glLoadIdentity();

         //I'm looking at the origin (center of my scene)
         gluLookAt (x, y, z, 0,0,0, 0.0, 1.0, 0.0); 

         rotateScene(rotateFlag);

         drawObjects();//draw Objects in Scene 

    }

I assign value to rotateFlag when i press left key or up key. It rotates the scene once only since my function rotateScene always applies glRotatef on the original arrangement of the scene which I should avoid. Does somebody knows how I can save the rotated scene so I can apply my function on it(the rotated scene) and rotate the scene everytime I press an arrow key? I hope I made myself clear.

I tried another solution by incrementing the angle in X and Y as I press the key

    If keypress left 
         angleX+=45;
    else if keypress up
         angleY+=45;

and adjust my rotateScene to

    void rotateScene(){
        glRotatef(angleX,1,0,0);
        glRotatef(angleY,0,1,0);
    }

Everything is going right when i performed rotation on individual axis, however, when I do Rotate on Y first then I perform rotate on X, the rotation of the scene is incorrect. Maybe this is because opengl executed rotate on X first before rotate on Y because of the ordering in the function call. I can't use this function properly since order in rotating the scene is important in my application.

Upvotes: 1

Views: 2921

Answers (1)

Tobias Schlegel
Tobias Schlegel

Reputation: 3970

Use glPushMatrix() to push a matrix to the matrix-stack and glPopMatrix() to retreive it back.

Upvotes: 1

Related Questions