Collision Detection
In this lesson, you’ll add collision detection to your game. To add the collision detection, you’ll use a method called .spritecollideany()
, which is read as “sprite collide any.” This method accepts a Sprite
and a Group
as parameters. It looks at every object in the Group
and checks if its .rect
intersects with the .rect
of the Sprite
. If so, then it returns True
. Otherwise, it returns False
:
130# Draw all sprites
131for entity in all_sprites:
132 screen.blit(entity.surf, entity.rect)
133
134# Check if any enemies have collided with the player
135if pygame.sprite.spritecollideany(player, enemies):
136 # If so, then remove the player and stop the loop
137 player.kill()
138 running = False
For more information about collision detection, check out the following resources from the pygame
documentation:
00:00 In this lesson, you’ll set up collision detection. As far as programming video games, checking for collisions can be difficult work, but PyGame makes this non-trivial math problem of determining when two sprites overlap easy. In fact, PyGame has several collision detection methods available.
00:18
We’re going to only explore one here: pygame.sprite.spritecollideany()
(sprite collide any). spritecollideany()
takes two arguments, and they are the Sprite
that you’re checking, and the Group
that you’re checking against. This method will check every object in the Group
if its .rect
(rectangle) intersects with the .rect
of the Sprite
.
00:42
And if it’s the case that it’s detected, then it’ll return True
, and then False
otherwise. Let me have you put it in place in your code.
00:51 I want to start off this by fixing the little error I had on line 83, just adding a space there. Okay. Down at line 130, right after you draw all the sprites, you’re going to go ahead and do this check.
01:15
You’re going to check if any enemies have collided with the player, and here you’re using if pygame.sprite.spritecollideany()
. Here is where you’re going to use the two different objects: the Sprite
, which is player
, versus the Group
, which is enemies
. Again, this is an if
statement.
01:33
If this is so, then remove the player and stop the loop. So this time, you’ll use player
and you’ll use that .kill()
method. And you’ll flip running
to now be False
,
01:52 which will kick you out of the game loop.
01:59 Have to reactivate my environment. Okay. Saving. After adding this collision detection, let me show you what it looks like when you play the game.
02:15 This time, I need to be a little more wary as I’m flying around here. And if I were to get hit by one of these fast moving ones—boom. I’m out. Great! All right, so a lot of the basic functionality is there.
02:30 So, the little rectangles flying around the screen are a little dull looking. Let’s spruce it up some more with actual images, and that’s in the next lesson.
Become a Member to join the conversation.