Bouncing algorithms are often used in arcade games such as Pong or Breakout.
To understand how to implement a bouncing algorithm, it is essential to understand how the computer controls the trajectory of a sprite (e.g. ball) on the screen. Arcade games are based on a frame based animation where the screen is refreshed every x milliseconds. Moving sprites are positioned using (x,y) coordinates and have a velocity vector (Vx,Vy) which specifies the delta in pixels to apply to the (x,y) coordinates of a sprite between two frames:
- frame n: Sprite Coordinates: (x,y)
- frame n+1: Sprite Coordinates: (x+Vx,y+Vy)
As the sprite moves across the screen, it may need to bounce against another sprite or against the edge of the screen.
Let’s investigate how the velocity vector is affected when the sprite bounces against vertical and horizontal walls/edges.
Python Code
The following Python code implements a bouncing algorithm against all 4 edges of the canvas.