In this blog post we will investigate how to implement a bouncing algorithm used either in a platform game when the main sprite collides with a platform or in a breakout game when the ball bounce against a brick.
(x,y) coordinates and velocity vector
In a frame based game, each sprite can be positioned on the screen based on its (x,y) coordinates. Each sprite can also be allocated a velocity vector. The velocity vector consists of two values (Vx, Vy) which represents the variation in pixels of the (x,y) coordinates of the sprite between two frames.
A collision occurs when two sprites are overlapping. Different algorithms can be used to detect such collisions. When creating a game with a library such as the Pygame library, you can re-use built-in collision detection algorithms without the need to implement these yourself.
A collision will impact the velocity vectors of the sprites involved in the collision. In a platform game or breakout game, we can assume that the platform or the brick will remain static. However, the collision will impact the velocity vector of the main character or the bouncing ball. Note that in a pool game the collision between two balls would impact the velocity vectors of both sprites involved in the collision!
The change in direction will depends on which edge of the platform/brick is being hit first and on the initial direction of the sprite when it collides with the platform.
Let’s investigate one approach that could be used in both our games:
Implementing a Bouncing Algorithm
This approach consists of considering 8 possible different collisions and their impact on the velocity vector of the bouncing sprite.
So, to implement an effective bouncing algorithm of a sprite against this platform, we must first identify the position of the sprite, relatively to the platform to distinguish the 8 possible areas. In the case of a rectangular platform, we can use the following comparisons between the (x,y) coordinates of the centre of our sprite with the top, right, bottom, left coordinates of our platform.
The following pseudocode demonstrates how the bouncing algorithm can be implemented. Though it only covers the first three scenarios, you should be able to complete this algorithm further to cater for all 8 scenarios.
Landing on a platform
Note that the above pseudocode is used to make our sprite bounce against the platform which would be suitable for the breakout game and in most cases for a platform game. However, with a platform game. When the sprite lands on a platform (case 2 in the above diagram/pseudocode) we may not want the sprite to bounce back but instead we want the sprite to remain on top of the platform. In this case the pseudocode for this scenario would be as follows: