Collision detection
Find out when things touch, using rectangles, circles, pixel-perfect masks and sprite groups, and learn how to respond so objects don't pass through walls.
On this page
What you'll learn
- Rectangle, point and circle collision checks
- Pixel-perfect collisions with masks
- Sprite group collision helpers
- Resolving collisions axis by axis so objects stop at walls
Prerequisites: Images and sprites.
Try the shapes interactively in the collision visualizer while you read.
Rectangles: the workhorse#
Axis-aligned rectangles are fast to test and good enough for most games.
player.colliderect(wall) # True if the two Rects overlap
player.collidepoint(mouse_pos) # True if a point is inside
player.collidelist(walls) # index of the first hit, or -1
player.collidelistall(walls) # indexes of all hits
overlap = player.clip(wall) # the overlapping area as a RectTwo rectangles overlap when each one's left edge is left of the other's right edge and each one's top is above the other's bottom. Note that a Rect's right and bottom are one pixel past its last pixel, so rectangles that only share an edge do not collide.
Circles: distance checks#
Round objects such as balls and coins feel unfair with rectangle hit boxes, because the corners register hits that look like misses. Two circles touch when the distance between centres is at most the sum of their radii:
if pygame.Vector2(a_center).distance_to(b_center) <= a_radius + b_radius:
...Comparing squared distances (distance_squared_to) skips a square root and is faster with many objects.
Pixel-perfect: masks#
A mask records which pixels of a Surface are solid. pygame.mask.from_surface(image) builds one from the image's alpha channel. Mask collisions are exact but slower, so a common pattern is a cheap rect test first, then the mask test only for objects whose rects overlap. pygame.sprite.collide_mask does exactly that.
"""Rect, circle and mask collisions side by side, plus group collisions."""
import pygame
WIDTH, HEIGHT = 640, 480
pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
clock = pygame.time.Clock()
font = pygame.font.Font(None, 24)
def make_star(size, color):
surf = pygame.Surface((size, size), pygame.SRCALPHA)
c = size / 2
points = []
for i in range(10):
r = c if i % 2 == 0 else c * 0.42
v = pygame.Vector2(0, -r).rotate(i * 36)
points.append((c + v.x, c + v.y))
pygame.draw.polygon(surf, color, points)
return surf
class Star(pygame.sprite.Sprite):
def __init__(self, center):
super().__init__()
self.image = make_star(90, (244, 197, 49))
self.rect = self.image.get_rect(center=center)
self.mask = pygame.mask.from_surface(self.image) # pixel-perfect shape
class Cursor(pygame.sprite.Sprite):
def __init__(self):
super().__init__()
self.image = pygame.Surface((24, 24), pygame.SRCALPHA)
pygame.draw.circle(self.image, (91, 147, 230), (12, 12), 12)
self.rect = self.image.get_rect()
self.radius = 12 # used by collide_circle
self.mask = pygame.mask.from_surface(self.image)
star = Star((480, 240))
cursor = Cursor()
wall = pygame.Rect(80, 180, 160, 120)
ball_center, ball_radius = pygame.Vector2(320, 360), 40
stars = pygame.sprite.Group(star)
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
cursor.rect.center = pygame.mouse.get_pos()
rect_hit = cursor.rect.colliderect(wall)
circle_hit = ball_center.distance_to(cursor.rect.center) <= ball_radius + cursor.radius
box_hit = bool(pygame.sprite.spritecollide(cursor, stars, False)) # rect test
mask_hit = bool(pygame.sprite.spritecollide(cursor, stars, False, pygame.sprite.collide_mask))
screen.fill((20, 26, 46))
pygame.draw.rect(screen, (232, 93, 82) if rect_hit else (90, 110, 150), wall)
pygame.draw.circle(screen, (232, 93, 82) if circle_hit else (90, 110, 150), ball_center, ball_radius)
pygame.draw.rect(screen, (232, 93, 82) if box_hit else (60, 70, 100), star.rect, 1) # star's rect
stars.draw(screen)
screen.blit(cursor.image, cursor.rect)
lines = [f"Rect: {rect_hit}", f"Circle: {circle_hit}", f"Star rect: {box_hit}", f"Star mask: {mask_hit}"]
for i, line in enumerate(lines):
screen.blit(font.render(line, True, (230, 236, 247)), (16, 16 + i * 24))
pygame.display.flip()
clock.tick(60)
pygame.quit()
Move the cursor into a corner of the star's bounding box: the rect test reports a hit while the mask test correctly says no.
Sprite group helpers#
| Function | Returns |
|---|---|
pygame.sprite.spritecollide(sprite, group, dokill) | list of sprites in group touching sprite |
pygame.sprite.spritecollideany(sprite, group) | the first hit or None (fastest) |
pygame.sprite.groupcollide(g1, g2, dokill1, dokill2) | dict mapping each hit sprite in g1 to the sprites it hit in g2 |
pygame.sprite.collide_rect, collide_circle, collide_mask | pass as collided= to change the test |
collide_circle uses a radius attribute on each sprite if present.
Responding to collisions: stopping at walls#
Detecting a hit is half the job. If a player moves into a wall you must push them back out. The reliable way is to move one axis at a time:
player.x += vel_x
for wall in walls:
if player.colliderect(wall):
if vel_x > 0:
player.right = wall.left
elif vel_x < 0:
player.left = wall.right
player.y += vel_y
for wall in walls:
if player.colliderect(wall):
if vel_y > 0:
player.bottom = wall.top # landed on something
vel_y = 0
elif vel_y < 0:
player.top = wall.bottom # bumped the ceiling
vel_y = 0Resolving x and y separately tells you which side was hit, so landing, wall sliding and head bumps all work. The platformer tutorial builds a full character controller on this idea.
Fast objects and tunnelling#
An object moving 40 pixels per frame can jump straight over a 20-pixel wall without ever overlapping it. Fixes: cap speeds, use smaller physics steps (see game physics), or test the line of travel with Rect.clipline(start, end).
Common mistakes#
- Removing from a list while looping over it skips items. Loop over a copy (
for coin in coins[:]) or build a new list. - Stale masks: if a sprite's image changes (animation, rotation), rebuild its mask.
- Hit boxes larger than the art feel unfair. Shrink them with
rect.inflate(-10, -10)for collision tests. - Collision then movement: check collisions after moving, in the same frame, so you never draw an object inside a wall.
Practice exercises#
- Use
inflateto give the player a smaller hit box than its image and draw both for debugging. - Make a ball bounce off the four sides of a rectangle, reversing the right velocity component.
- Count how many stars the cursor touches using
spritecollidewithcollide_circle. - Use
Rect.cliplineto detect a laser beam hitting a box.