Bouncing Algorithm

pong-gameBouncing 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 positionned 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)

velocity-vector

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.

Right Wall/EdgeLeft Wall/EdgeTop Wall/EdgeBottom Wall/Edge
bouncing-algorithm-right
bouncing-algorithm-left
bouncing-algorithm-top
bouncing-algorithm-bottom

Python Code


The following Python code implements a bouncing algorithm against all 4 edges of the canvas.

Share Button
Posted in Computer Science, Computing Concepts, Python - Advanced, Python Challenges Tagged with:

Our Latest Book

Follow this blog