
In this Pygame Collision Detection tutorial, you will learn how to detect when two game objects touch each other.
Until now, your player can move around the screen, and your enemy moves automatically. But there is one problem. Even if the player touches the enemy, nothing happens.
In real games, touching an enemy can:
- Lose a life
- End the game
- Reduce health
- Restart the level
To make this happen, we need collision detection. By the end of this lesson, your game will detect when the player touches the enemy.
What Is Collision Detection?
Collision Detection means checking whether two game objects are touching each other. For example:
- ๐ Car hits another car
- ๐ฆ Player touches a coin
- ๐ Rocket hits an asteroid
- ๐ง Hero touches a zombie
- โฝ Ball enters the goal
All of these are examples of collisions.
How Does Pygame Detect a Collision?
Pygame uses Rectangles (Rect) to check whether two objects overlap.
Think of every image as being inside an invisible box.
When two invisible boxes touch, Pygame reports a collision.
You don’t see these boxes, but they are always there.
Step 1: Create Player Rectangle
After setting the player’s position, add:
player_rect = player.get_rect(topleft=(x, y))
This creates a rectangle around the player image.
Step 2: Create Enemy Rectangle
Add:
enemy_rect = enemy.get_rect(topleft=(enemy_x, enemy_y))
Now the enemy also has an invisible rectangle.
Step 3: Check for Collision
Now add:
if player_rect.colliderect(enemy_rect):
print("Collision Detected!")
Run the program.
Move the player toward the enemy.
When they touch, the message appears in the terminal.
Congratulations!
You just detected your first collision.
Complete Program
import pygame
pygame.init()
screen = pygame.display.set_mode((800,600))
pygame.display.set_caption("Collision Detection")
background = pygame.image.load("images/background.png")
player = pygame.image.load("images/player.png")
enemy = pygame.image.load("images/enemy.png")
x = 350
y = 250
enemy_x = 0
enemy_y = 100
enemy_speed = 3
running = True
while running:
screen.blit(background,(0,0))
keys = pygame.key.get_pressed()
if keys[pygame.K_RIGHT] and x < 736:
x += 5
if keys[pygame.K_LEFT] and x > 0:
x -= 5
if keys[pygame.K_UP] and y > 0:
y -= 5
if keys[pygame.K_DOWN] and y < 536:
y += 5
enemy_x += enemy_speed
if enemy_x > 800:
enemy_x = -64
player_rect = player.get_rect(topleft=(x, y))
enemy_rect = enemy.get_rect(topleft=(enemy_x, enemy_y))
if player_rect.colliderect(enemy_rect):
print("Collision Detected!")
screen.blit(player,(x,y))
screen.blit(enemy,(enemy_x,enemy_y))
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
pygame.quit()
Understanding get_rect()
This line:
player_rect = player.get_rect(topleft=(x, y))
creates a rectangle around the player image.
The rectangle moves with the player.
The same happens for the enemy.
Understanding colliderect()
This is the most important line in today’s lesson.
player_rect.colliderect(enemy_rect)
It simply asks:
“Are these two rectangles touching?”
If the answer is Yes, it returns:
True
Otherwise, it returns:
False
Show a Better Message
Instead of:
print("Collision Detected!")
Try:
pygame.display.set_caption("Game Over!")
Now, when the player touches the enemy, the game window title changes.
This makes the game feel more interactive.
Mini Project
Create a game where:
- The player moves using arrow keys.
- The enemy moves automatically.
- A message appears when they touch.
Practice Challenge
Challenge 1
Change the message to:
print("Oops! You touched the enemy.")
Challenge 2
Increase the enemy speed.
Can you still avoid it?
Challenge 3
Add a second enemy and check collisions with both enemies.
Common Mistakes
Collision never happens
Make sure you create the rectangles inside the game loop, after updating the player’s and enemy’s positions.
Collision happens in the wrong place
Check that get_rect() uses the correct coordinates:
topleft=(x, y)
Terminal shows nothing
Move the player until it actually touches the enemy.
Remember, the invisible rectangles must overlap.
Best Practice
Create the rectangle after updating the object’s position.
This keeps the rectangle in the correct location.
Good order:
- Move the player
- Move the enemy
- Create rectangles
- Check collision
- Draw everything
What You Learned Today
Today you learned:
- What collision detection is
- Why games need collision detection
- How
get_rect()works - How
colliderect()detects touching objects - How to trigger an action after a collision
Quick Revision
- What is collision detection?
- Which function creates a rectangle around an image?
- Which function checks whether two rectangles touch?
- What does
colliderect()return if two objects overlap?
What’s Next?
In Lesson 12: Collect Coins in Pygame, you will learn how to add coins to your game. When the player touches a coin, it will disappear, and you’ll prepare your game for a scoring system.
Frequently Asked Questions (SEO & AEO Optimized)
What is Pygame Collision Detection?
Pygame Collision Detection is the process of checking whether two game objects are touching or overlapping.
How do I detect a collision in Pygame?
Create rectangles with get_rect() and compare them using the colliderect() method.
What does colliderect() do in Pygame?
The colliderect() method returns True when two rectangles overlap and False when they do not.
Why is collision detection important in games?
Collision detection allows games to detect events such as collecting coins, touching enemies, scoring points, and ending the game.
Can I detect collisions between images?
Yes. Each image can have a rectangle created with get_rect(), and those rectangles can be checked for collisions.
Why isn’t my collision working?
Common causes include creating rectangles outside the game loop, using incorrect coordinates, or checking collisions before updating object positions.
Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.
Shubhranshu Shekhar is a coding instructor, mentor, and founder of VSIT Delhi with 20+ years of teaching experience (since 2004). He has guided many students who are now working in multinational companies and specializes in Full Stack Development, Python, Digital Marketing, and Data Analytics.