How it works...

GLUT is initialized and a top-level window is created with the label, Animating a ball. The initial position of the window is set at 0,0, that is, at x=0 and y=0 coordinate location. The window size is specified with 1,000 px of width and 1,000 px of height. The callback function, animball, is invoked to display a bouncing ball.

In the animball callback function, the values of the color buffers are cleared. The color for drawing the bouncing ball is set to green. Because the ball will be drawn using small points or dots, the glPointSize is set to 1 px.

The GL_PROJECTION is set as the current matrix in order to enable parallel and perspective projections. Also, a two-dimensional orthographic viewing region is set up, defining the left and right vertical clipping planes and the bottom and top horizontal clipping planes.

To display a bouncing ball, we first make the ball drop down on the floor and then bounce back up. To make the falling ball, we draw a ball at some x, y coordinate. After drawing that ball, we clear the screen and redraw the ball just below the original coordinate, that is, after lowering the y coordinate. Clearing and redrawing the ball with successively falling y coordinates repetitively and swiftly will make the ball appear as if it's falling. We will do the reverse to make the ball bounce up. That is, the ball is drawn, the screen is cleared, and the ball is redrawn at successively higher y coordinates. The radius of the ball is assumed to be 100 px (but it can be any radius).

To compile the program, start the X server and give the following command to compile the program:

gcc ballanim.c -lGL -lGLU -lglut -lm -o ballanim

If no error appears, that means the ballanim.c program has successfully compiled into an executable file: ballanim.exe. This file is executed using the following command:

$./ballanim

We will get the output as shown in the following screenshot:

Figure 12.5

Voilà! We have successfully created an animated bouncing ball.