Bouncing ball in pygame
Martin McBride, 2021-03-09
Tags game development sprite animation
We created a moving sprite in the previous article, but this time we will do something a bit more interesting. Rather than disappearing off the edge of the screen, we will make our sprite bounce off the edges.
Modifying the sprite behaviour
We will make a couple of changes to the
class Ball(pg.sprite.Sprite): def __init__(self, pos): super(Ball, self).__init__() self.image = pg.image.load(os.path.join('resources', 'ball.png')) self.rect = self.image.get_rect() self.rect.center = pos self.velocity = [5, 5] def update(self): if self.rect.left < 0 or self.rect.right >= SCREEN_WIDTH: self.velocity *= -1 if self.rect.top < 0 or self.rect.bottom >= SCREEN_HEIGHT: self.velocity *= -1 self.rect.move_ip(self.velocity)
The first thing we have done is make the initial velocity
[5, 5], so that the ball travels a bit faster.
But the main changes is in the
update method. We test the position of the rectangle containing the ball, and if we are at the edge of the screen we reverse its velocity to make it start travelling in the opposite direction.
Specifically, if the left hand edge of the rectangle,
rect.left, is less that zero, or if the right hand edge,
rect.right, is greater than or equal to the screen width, then we know that the ball has hit the left or right edge of the screen. So we reverse the velocity of the x direction.
Here is an illustration of the ball approaching the right hand edge of the screen. It has a velocity of [5, 5], so it is travelling diagonally towards the bottom right. When it hits the edge, its x velocity is reversed, making its velocity [-5, 5]. This means it is travelling diagonally towards the bottom left:
We do a similar check to see if the ball hits the top or bottom of the screen, and we reverse the velocity of the y direction if that happens.
It is possible that the ball could hit two sides at the same time. For example if it exactly hits the top left corner of the screen. That is no problem - the two if statements will both execute, and the ball will change direction in both x and y axes.
You might expect that we would need to modify the main loop to make our sprite bounce, but in fact we don't. The behaviour is totally contained within the
The source code is available on github as bouncingsprite.py.