Skip to content
Tutorials Center
My learning

Topics

Lesson 18 of 41 ยท Sprites and Collision

Collision Detection in Pygame

Detect collisions in Pygame with Rect.colliderect, circle collisions, spritecollide and groupcollide. Shrink hitboxes, choose a collision shape and avoid tunneling.

Collision detection answers the question every game asks: do these two things touch? A bullet hits an enemy, the player grabs a coin, the ball hits a paddle, a character walks into a wall. Pygame offers several tools, from simple rectangle tests to group-wide checks, and choosing the right one affects both how fair the game feels and how fast it runs.

Rectangle collision

The simplest test is Rect.colliderect, which you met in Colors and Rects:

Python
if player.rect.colliderect(coin.rect):
    score += 1
    coin.kill()

Rectangles overlap when they share at least one pixel. Touching edges do not count. A rectangle test is extremely fast, so use it as your default and refine only if players notice that hits look unfair.

Other point and list tests:

Python
button.collidepoint(mouse_pos)              # point inside rect
player.collidelist(wall_rects)              # index of first hit, -1 for none
player.collidelistall(wall_rects)           # all hits

Hitboxes: smaller than the image

Sprites are usually surrounded by transparent pixels, so a full-image rectangle makes players die to bullets that visibly miss. Give sprites a separate, smaller hitbox:

Python
self.rect = self.image.get_rect(center=(x, y))
self.hitbox = self.rect.inflate(-20, -16)      # shrink by 20 x 16 pixels

Update hitbox.center = rect.center whenever the sprite moves, then use hitbox for collisions. Most shooters make the player's hitbox much smaller than the ship, so near misses feel exciting instead of cheap.

Circle collision

For round objects (balls, planets, bubbles), two circles overlap when the distance between their centers is smaller than the sum of the radii:

Python
distance = pygame.Vector2(a.center).distance_to(b.center)
hit = distance < a.radius + b.radius

Comparing squared distances avoids a square root and is faster:

Python
hit = pygame.Vector2(a.center).distance_squared_to(b.center) < (a.radius + b.radius) ** 2
Python Rect versus circle collision

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Sprite collision functions

pygame.sprite provides ready-made checks that work with groups, so you rarely write loops by hand.

spritecollide

spritecollide(sprite, group, dokill) returns a list of sprites in group that collide with sprite. When dokill is true they are removed from all groups:

Python
hits = pygame.sprite.spritecollide(player, coins, True)     # collect coins
for coin in hits:
    score += coin.value

if pygame.sprite.spritecollide(player, enemies, False):     # just test
    player.take_damage()

spritecollideany

spritecollideany(sprite, group) returns one colliding sprite or None: cheaper when you only need a yes/no.

groupcollide

groupcollide(group1, group2, dokill1, dokill2) checks every sprite of one group against every sprite of the other and returns a dictionary {sprite_from_group1: [colliding sprites from group2]}:

Python
hits = pygame.sprite.groupcollide(bullets, enemies, True, True)   # bullets and enemies both die
for bullet, enemies_hit in hits.items():
    score += 10 * len(enemies_hit)

Choosing the collision shape

All three accept an optional collided callback that changes how two sprites are compared:

Callback Uses
(default) sprite.rect (rectangles)
pygame.sprite.collide_rect_ratio(0.7) Rects scaled to 70 percent
pygame.sprite.collide_circle A circle around each rect (uses sprite.radius if present)
pygame.sprite.collide_circle_ratio(0.8) Circles scaled
pygame.sprite.collide_mask Pixel-perfect (see Masks and Pixel-Perfect Collision)
Python
hits = pygame.sprite.spritecollide(player, asteroids, False, pygame.sprite.collide_circle)

You can also pass your own function that takes two sprites and returns a bool (for example, one that compares hitbox rects).

Try it: bullets versus enemies

This runs a complete mini scenario with sprite groups and groupcollide, no window needed.

Python groupcollide and spritecollide

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Try it: circle callback

Round asteroids have a lot of empty corner space. The collide_circle callback fixes the unfair hits of rectangles, and you can give a sprite a radius attribute to control the size.

Python collide_circle with a radius

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Tunneling: when fast objects skip through

Collision checks happen once per frame. A bullet moving 50 pixels per frame can jump from one side of a 10 pixel wall to the other without ever overlapping it. Fixes:

  1. Limit speed to less than the thinnest obstacle per frame.
  2. Sub-step: move in several small steps and test after each.
  3. Sweep the movement: test the rect that covers the whole path (old_rect.union(new_rect)).
  4. Use a fixed time step (see The Game Loop), so movement per step is bounded.

Performance

Checking every sprite against every other one is O(n squared). With a few hundred sprites it is fine, but for thousands:

  • Only check relevant pairs (bullets against enemies, not against each other).
  • Use collidelistall on a list of rects, which runs in C.
  • Use a spatial grid: put objects in cells of a fixed size and only compare objects in neighboring cells.
  • Do a cheap rect test first and an expensive pixel test only when the rects overlap.

Common mistakes

  • Using spritecollide(..., dokill=True) on the player group by accident.
  • Testing collisions with a sprite that is not in any group (works, but kill() does nothing).
  • Forgetting the collided callback needs a function, not a call: collide_circle, not collide_circle() (only the _ratio versions are called).
  • Relying on a full-image rect for characters with big transparent margins.
  • Checking collisions before moving, then wondering about a one-frame delay.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does pygame.sprite.spritecollide(player, coins, True) return?

    It returns a list of colliding sprites; dokill=True removes them from all groups.
  2. 2. What does groupcollide(bullets, enemies, True, False) do?

    The two booleans are dokill1 and dokill2 for the first and second group.
  3. 3. Why shrink a sprite's hitbox below its image size?

    A smaller hitbox makes hits match what players see.
  4. 4. What is tunneling?

    Collision is checked once per frame, so a large per-frame step can skip over an obstacle.
  5. 5. Which circle test is fastest?

    Squared distances avoid the square root.

Summary

  • Rect.colliderect is the fast default; touching edges do not collide.
  • Use smaller hitboxes or circles when the image shape is not rectangular.
  • spritecollide, spritecollideany and groupcollide check sprites against groups; dokill removes hits.
  • A collided callback changes the shape: rect ratio, circle or mask.
  • Guard against tunneling and keep collision checks cheap.

Next: Collision Response and Walls