Menu

Pygame Collision Detection: colliderect and More

Detect collisions in pygame with Rect methods: colliderect for two boxes, collidepoint for clicks, collidelist for many, plus circle collisions by distance and how to stop a player at a wall instead of passing through.

This page includes runnable editors. Edit, run, and see output instantly.

Most pygame games detect collisions with rectangles. Give every object a pygame.Rect, move it, then ask the Rect whether it overlaps another:

Press Play, click the game and collect coins with the arrow keys. When the boxes overlap, the coin jumps somewhere new.

Rect collision methods

MethodAnswers
a.colliderect(b)Do the two rectangles overlap?
a.collidepoint(x, y) or a.collidepoint(pos)Is the point inside? Clicks, bullets as points
a.collidelist(rects)Index of the first overlapping Rect in a list, or -1
a.collidelistall(rects)Indexes of all overlapping Rects
a.contains(b)Is b completely inside a?

Rectangles that only share an edge do not count as overlapping. For collisions between sprites in groups, see sprite collisions.

Stopping at a wall

Detecting a collision is half the job; often the player must also not pass through. The reliable way is to move and fix one axis at a time. After moving on x, any overlap must have come from horizontal movement, so you know which edge to push back:

Walk into the walls, then slide along them while holding two arrows: the player stops on one axis and keeps moving on the other. Platformers use the same idea, with gravity as the dy.

Circles

For round things (balls, planets, explosions) a rectangle is a poor fit at the corners. Two circles touch when the distance between their centers is less than the sum of their radii:

Move the pointer over the game: the big circle turns red when the small one touches it, exactly at the curve. Sprite groups can do the same with pygame.sprite.collide_circle.

Fast objects

A bullet moving 30 pixels a frame can jump over a 10 pixel enemy between two frames, so the overlap never happens. Make fast objects longer than their speed, split the move into smaller steps, or check the line the bullet traveled with rect.clipline(start, end).

Frequently Asked Questions

How do I check if two rectangles collide in pygame?

rect_a.colliderect(rect_b) returns True when they overlap. Keep a pygame.Rect for each object and test them every frame after moving.

How do I stop a player from walking through walls?

Move one axis at a time. Move on x, and if the player now overlaps a wall, set its right edge to the wall's left (or the other way round). Then do the same for y. Fixing both axes at once makes the player stick or jump.

How do I detect a collision between circles?

Two circles touch when the distance between their centers is less than the sum of their radii: pygame.Vector2(a).distance_to(b) < r1 + r2.

Coddy programming languages illustration

Learn to code with Coddy

Get started