Skip to content
Tutorials Center
My learning

Topics

Lesson 20 of 41 ยท Sprites and Collision

Masks and Pixel-Perfect Collision

Use pygame.mask for pixel-perfect collision. Build masks from surfaces, test overlap and overlap_area, use collide_mask with sprites, find outlines and combine with rect checks.

Rectangles and circles are fast but approximate. A spaceship shaped like an arrow, a bird with spread wings or a terrain silhouette overlaps its rectangle only partly, so rect collision reports hits where the pictures do not touch. When that matters, use a mask: a bitmap that remembers which pixels of an image are solid. Pygame can compare two masks and tell you if (and where) the solid pixels overlap. That is pixel-perfect collision.

What a mask is

A pygame.mask.Mask is a grid of bits, one per pixel: 1 means "solid", 0 means "empty". The usual way to get one is from a surface with transparency:

Python
image = pygame.image.load("ship.png").convert_alpha()
mask = pygame.mask.from_surface(image)         # opaque pixels become solid

By default, pixels with alpha above 127 count as solid (change it with the threshold argument). For a surface without alpha, you can use a colorkey, or build the mask yourself with Mask(size, fill=True) and then clear or set bits.

Useful attributes and methods:

Call Meaning
mask.get_size() Width and height
mask.count() Number of solid pixels
mask.get_at((x, y)) / set_at(...) Read or change one bit
mask.overlap(other, offset) First overlapping pixel (x, y) or None
mask.overlap_area(other, offset) Number of overlapping pixels
mask.overlap_mask(other, offset) A mask of the overlapping region
mask.outline() List of points along the border
mask.get_bounding_rects() Rects around each connected blob
mask.to_surface() Draw the mask back into a surface (for debugging)

The offset

overlap needs to know where the second mask sits relative to the first. The offset is (other_x - self_x, other_y - self_y), using the top-left corners of the two rects:

Python
offset = (enemy.rect.x - player.rect.x, enemy.rect.y - player.rect.y)
point = player.mask.overlap(enemy.mask, offset)
if point:
    print("pixel-perfect hit at", point)     # relative to the first mask

Getting the offset backwards (first minus second) is the most frequent bug.

Try it: a triangle that does not touch a square

Two shapes whose rectangles overlap but whose pixels do not. We build masks from surfaces drawn with alpha.

Python Mask overlap versus rect overlap

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.

At (8, 8) the rectangles overlap (a plain rect test would say "hit") but the masks do not; only masks tell the truth.

collide_mask with sprites

If your sprite has a mask attribute, pygame.sprite.collide_mask does the offset calculation for you and plugs into every sprite collision function:

Python
class Ship(pygame.sprite.Sprite):
    def __init__(self):
        super().__init__()
        self.image = pygame.image.load("ship.png").convert_alpha()
        self.rect = self.image.get_rect()
        self.mask = pygame.mask.from_surface(self.image)    # build ONCE

hits = pygame.sprite.spritecollide(ship, asteroids, False, pygame.sprite.collide_mask)

If a sprite has no mask, collide_mask builds one from image every time, which is slow: always create the mask in __init__.

Python spritecollide with collide_mask

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.

A ring is hollow: the pin in the middle is inside its rectangle (and circle) but passes through the hole. Only the mask sees that.

Rotated and scaled sprites need new masks

A mask is a snapshot of one image. If you rotate or scale the image, rebuild the mask for the new image and keep the rect centered:

Python
self.image = pygame.transform.rotate(self.original, angle)
self.rect = self.image.get_rect(center=self.rect.center)
self.mask = pygame.mask.from_surface(self.image)

Recomputing a mask is cheap for small images, but do not do it every frame for the same angle. Cache masks along with rotated images (a dictionary keyed by angle).

Performance: rect first, mask second

A mask test is much slower than a rect test. A good pattern is a broad phase and a narrow phase:

  1. Cheap check: rect.colliderect(other.rect).
  2. Only if that is true, run mask.overlap.

pygame.sprite.collide_mask already follows this idea internally (it exits early if the rects do not overlap), but when writing your own loops, add the rect test yourself.

Outlines and other mask tricks

Masks are not only for collision:

  • Silhouette or glow: mask.to_surface(setcolor=(255, 255, 255), unsetcolor=(0, 0, 0, 0)) creates a white version of a sprite, great for a hit flash.
  • Outline: mask.outline() returns border points to draw with pygame.draw.lines, e.g. to highlight a selected unit.
  • Terrain: keep a mask of the ground and check ground_mask.get_at((x, y)) to see if a point is in solid terrain (Worms-style destructible landscapes: clear bits with mask.erase).
  • Click detection on irregular shapes: mask.get_at((mouse_x - rect.x, mouse_y - rect.y)) tells whether the click hit a visible pixel. Check bounds first, because get_at raises IndexError outside the mask.
Python Click on an irregular shape

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.

Common mistakes

  • Building a mask every frame instead of once.
  • Wrong offset sign: use (other.x - self.x, other.y - self.y).
  • Using from_surface on an opaque image (every pixel solid, so it acts as a rect).
  • Forgetting to rebuild the mask after rotating or scaling.
  • Calling mask.get_at with coordinates outside the mask.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does pygame.mask.from_surface(image) treat as solid by default?

    The default threshold is 127 for the alpha channel, so mostly opaque pixels are solid.
  2. 2. What is the offset in mask1.overlap(mask2, offset)?

    It tells Pygame where the second mask sits in the first mask's coordinates.
  3. 3. Which sprite attribute does pygame.sprite.collide_mask look for?

    A mask attribute is used if present; otherwise one is built each call, which is slow.
  4. 4. Why do masks need rebuilding after rotating a sprite image?

    A mask is a bitmap of one specific image; a rotated image has different solid pixels.
  5. 5. What is a good performance pattern for pixel-perfect collision?

    A cheap broad-phase check avoids most expensive mask comparisons.

Summary

  • A mask stores which pixels of an image are solid; from_surface builds one from alpha.
  • overlap, overlap_area and collide_mask give pixel-perfect collision; mind the offset direction.
  • Build masks once and rebuild them after rotating or scaling.
  • Use a rect test as a quick filter before a mask test.
  • Masks also serve for irregular click areas, outlines and terrain.

Next: Sound Effects and Music in Pygame