Background

bouncy is a simple 2D bouncing balls simulation built in C++ using SDL3 for rendering. It simulates balls bouncing around in a box — colliding with the walls and each other.

Initial State

The simulation starts with a random number of balls, where each ball has a random:

Running State

As the simulation runs, the balls bounce around, interacting with each other and the walls. The user can add in new balls (up to a max ball count) using + key and remove balls using the - key. Finally, they can quit the simulation by pressing ESC

Physics

The main “physics” here are collisions between the balls with themselves and with the walls.

We are dealing with 2D objects (in 2D space); however, we model the objects as 1D (in 2D space) for computing the collision results. From a realism perspective, this is incorrect modeling, but it keeps the equations simple and “good enough” for this program.

Ball-Wall Collisions

This is a simplest collision to deal with, where the ball is colliding with the wall. This is modeling as a 1D elastic collision against an immovable wall, so the ball’s speed remains the same, just the direction changes.

$$ \vec{v}_f = \vec{v}_i-2(\vec{v}_i \cdot \hat{n})\hat{n} $$

The ball’s new velocity $\vec{v}_f$ is a “reflection” over the wall’s normal vector $\hat{n}$. Computing the normal vector for the wall is quite straightforward:

$$ \hat{n} = \frac{-B\hat{\imath} + A\hat{\jmath}} {\sqrt{A^2 + B^2}} $$

Where the vector representing the wall is $\vec{s} = A\hat{\imath} + B\hat{\jmath}$. There are two possible normal vectors to a wall; however, we only use this one and carefully craft the wall vectors to ensure that by selecting this variant we always get the “inward” facing normal.

Ball-Ball Collisions