norman
norman

Reputation: 5556

Smooth movement direction transitions in OpenGL

I have an OpenGL program with a little character that can be moved around the screen with the arrow keys. When one changes direction, the character changes its orientation accordingly, basically like this:

 //Pressing the up arrow to go in the up direction 

 if(prevSwimDirection == RIGHT)
         swimAngle = 90;
 ...
 glutPostRedisplay(); 

The swim direction is taken care of in the display function elsewhere in the code:

  if(changesMode == SWIM_AROUND)
     glRotatef((GLfloat)swimAngle, 0.0, 0.0, 1.0);

Of course, this causes instant, abrupt direction changes. I tried to smooth them out like this, but no luck:

   if(prevSwimDirection == RIGHT)
     for(double i = swimAngle; i < 90; i += 0.00001){
       swimAngle = i;
       glutPostRedisplay();
     }

I tried incrementing the i with various values and eventually realized that the calculations appear to be carried out BEFORE the redisplay, even though I am calling glutPostRedisplay() throughout the loop. In other words, it still changes directions abruptly, but with a slight initial delay.

Is there a way to make this work properly (or, better yet, efficiently)?

Upvotes: 0

Views: 1141

Answers (1)

datenwolf
datenwolf

Reputation: 162164

glutPostRedisplay does not cause an immediate redraw, but just sets a flag, that the display function will be called, the next time the event loop iterates.

As a general rule, you should never play animations from input event handlers. Instead you should set animation parameters, in your case the new target orientation, that's applied in the animation code between display function calls. Measure the time between display calls and advance the animation accordingly. Never play a animation by iterating through a loop!

Upvotes: 1

Related Questions