OpenGL: A Simple Animation
A Simple Animation
This C++ OpenGL video tutorial demostrates how to create a simple animation. The main purpose of this lesson is to present the basic elements used in an animation loop in OpenGL with GLUT. We start with our C++ code from OpenGL and make changes to that code for this lesson. Below, we have all of the lines that have been changed for this lesson from the lesson 1 highlighted in white. The rest of the code is the same as lesson 1.
With these changes made to our code, our previous diagonal line is now animated so that the x-coordinates of the endpoints alternate between the 0 and 1 in opposite directions. The variable gfPosX is used as the x-position of the lower endpoint, and (1 - gfPosX) as the x-position of the upper endpoint. The value of gfPosX is changed by the value of gfDeltaX at each frame. The value of gfDeltaX changes sign whenever gfPosx reaches 0 or 1 by the "if" statement that we added. This keeps gfPosX and, by extension, the x-coordinates of the endpoints from leaving the range [0, 1].
The animation is created via an implied loop. In this case, the loop is created by redisplay event. By calling glutDisplayFunc() with our Draw() function as the argument, we set Draw() to be called everytime the window needs to be redisplayed. For example, Draw() is originally called the when the window is drawn the first time. Since this sends a redislay message to the message queue. When this message is handled, Draw() is called, which, in turn, posts a redisplay message at the end of the function when glutPostRedisplay() is called. This completes the loop.
This simple animation is primarily for illustration and lacks some finishing touches: double buffering, timing, etc. Depending on the speed of computer that the code runs, the animation may look much faster or slower. This inconsistency will be addressed in the future. For the present purposes, the value of gfDeltaX may be changed to alter the speed of the animation to get a reasonable looking result.