Detecting collisions

Pygame has a couple of really handy built in collision detection functions you can use: colliderect and collidelist are the main two I’ll discuss here.

Collide with a rectangle

It works by providing the coordinates to two sets of rectangles, and if there is any overlap it will trigger the collision. We’ve drawn rectangles using pygame.draw.rect but you can also create rectangle variables. These can then be used for collision detection as well as drawing on screen (though once you start using images/sprites you probably won’t even draw them).

To create a rectangle variable

my_rect = Rect( x, y, width, height )

To then draw that rectangle use

pygame.draw.rect( window, COLOR, my_rect )

To check if two rectangles overlap (collide) at all, the “if” statement would look like this:

if Rect( x, y, w, h ).colliderect( Rect( x, y, w, h ) ):
   print("There is a collision")

Example code with a couple of rectangle variables would be:

ball = Rect( ball_x, ball_y, 20, 20 )
paddle = Rect( paddle_x, 470, 60, 20 )

if ball.colliderect( paddle ):
   print("Collision detected")

Look back at the “Basics Pong using mousemotion” sample code and you’ll spot an example of it being used.

Collide with a list of rectangles

This works very similar as colliderect, the difference being that instead of checking if one rectangle is overlapping another single rectangle, it can check to see if a rectangle is overlapping any items in a list of rectangles!

This is very useful in a game scenario where you might have multiple enemies, bombs or bullets to avoid – you can check your player isn’t touching any of them in one line of code!

The key difference is that instead of returning True or False, the function will return a number to indicate which item in the list there is collision with, or -1 if there is no collision.

A crude illustration of it’s use might look like:

baddies = [
   Rect( 0, 50, 50, 50 ),
   Rect( 50, 200, 50, 50 ),
   Rect( 200, 100, 50, 50 )
me = Rect( 75, 25, 50, 50 )
if me.collidelist(baddies) >= 0:
   print("Uh oh! A baddie has caught you!")

To see this in use properly, look at Space Invaders in the project starters section. Look for the comment “Check for collisions between bullets and aliens ” and you’ll see collidelist in action.