code4fun
code4fun

Reputation: 2739

OpenGL glTranslatef/glRotatef not working as I expect

I am trying to create a polygon and translate/rotate it when the mouse button is released. I am able to do this if I redraw my whole polygon again by using glBegin and glEnd but I am not sure if I really need this as I have already drawn the polygon on the screen once and just want to use the same object and apply rotation/translation to it.

I am putting a snippet below.

if(state == GLUT_UP){

    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
    glClear(GL_COLOR_BUFFER_BIT);
    glPushMatrix();
    glRotatef(90,0,0,1);
    //  glTranslatef(50,-50,0);
    /*
    glBegin(GL_POLYGON);
    glVertex2i (-40,40) ; //Specify li ne - se gme nt ge ometry .
    glVertex2i (-30 , -40) ;
    glVertex2i (0 , 20) ;
    glVertex2i (40 , 35) ;
    glEnd() ;
    */
    glClear(GL_COLOR_BUFFER_BIT);
    glPopMatrix();
    glutSwapBuffers();
    //  glutPostRedisplay();
}

Upvotes: 2

Views: 1641

Answers (2)

nyumerics
nyumerics

Reputation: 6547

You donot need to write the whole code again:

In your display function (the same void function that you use as an argument to register the callbacks to glut window as glutDisplayFunc(display) ) put your code snippet above.

Inside your glPushMatrix()..glPopMatrix() sequence, put a variable(preferably GLfloat type) angle inside glRotatef() call along with your rotating axis. You can do the same for glRotatef() arguments.

If you want to rotate or translate using mouse or keyboard, then use glutMouseFunc() or glutKeyboardFunc() to register the callbacks with GLUT. If you want an animation, then you can register a function with glutIdleFunc().

The code snippet will be:

void handler(...){
angle+=some_value;

//angle reset not so necessary but good,
 if you somehow are using that angle value somewhere else
  if(angle>360)
  angle=0;

glutPostRediplay();
}

keyboard:

handler(unsigned char key, int x, int y);

mouse:

handler(int button, int state, int x, int y);

idle function (for continuous animation)

handler(void);

Upvotes: 0

datenwolf
datenwolf

Reputation: 162164

Please speak with me: "I'll never put OpenGL drawing calls into event handlers again!"

In a event handler you set some variable according to the event, then issue a redrawing call and in the rendering function you draw according to the content of the variables.

Update:

Also OpenGL does not "rememer" what you draw. You send drawing commands, OpenGL does its deed and then forgets about it. The only trace left are the fragments turned to pixels on the framebuffer. But the framebuffer contents are not affected by transformation or any OpenGL state changes. Only drawing affects the framebuffer.

Upvotes: 12

Related Questions