Bouncing Ball animation C++

A glfw application with C++11

This is how our bouncing ball animation will look like, sorry if its too bright.

bouncing ball animation c++


glfw has a C API but as a C++ application use this API in a simple inheritance-based little framework.
glfw_app BASE CLASS

This base class is simple: It manages a glfw window and their OpenGL context for us, wraps (and currently hides) the event and rendering loop, finally and provides us some polymorphic functions to say what to do when a key is pressed, when the window is resized, etc.

Here’s the declaration of the bouncing ball glfw application:


We have ball coordinates, ball speed, and its radius. There is also a gravity constant, since we want our ball to bounce. 

The template stuff on the constructor is a variadic template with perfect forwarding, just to bypass all the arguments to the base class constructor.

The on_keydon() callback is not complex: Just closes the window when the user presses ESC:

Now this is the body of our rendering loop:


Note how the ball is projected. The visible area of our OpenGL scene (The area which matches the viewport) goes from -1 to 1 in both axes, where -1 is the bottom-left corner of our window, and 1 is its top-left. 

Working with coordinates [-1,1] makes it simple to deal with window bounds, since they are independent of the window’s size.
Check how the animation works:

The ball’s position and speed are updated following the equations v’ = v + a*t and p’ = p + v * t, where v is velocity (speed), a is acceleration (The gravity constant), and t is time.

Time is measured in frames, so in all the equations t is one. That’s why there’s no t in our code. If you want a stable simulation (independent of frame rate) you should use a more complex technique, like those described in this article.

If the ball goes out of the window bounds, that is, y_ball – radious is less than -1, we should make the ball go upwards: Set its vertical speed as positive:

Also apply gravity. Don’t apply acceleration when the ball bounces.

The final step is to draw the ball: Draw a white “circle” (a regular polygon) using GL_POLYGON:


Now here the main() function

glfw is a great library to write OpenGL applications. Its C API is clear and simple, and making it work in the C++ way can be done with just a little effort.We learnt here how to make a little framework to write simple OpenGL applications in a OO way. Encapsulating the most common tasks in a base class reduces noise in our simple OpenGL examples.

Leave a Reply