So, I've been prototyping a game, and I've been using sprite collision, and it's not cutting it any more. I read up on the documentation about masks and overlap area: https://www.pygame.org/docs/ref/mask.html#pygame.mask.Mask.overlap_area

How exactly do I use this? The documentation says "This can be used to see in which direction things collide, or to see how much the two masks collide. An approximate collision normal can be found by calculating the gradient of the overlap area through the finite difference."

I don't quite follow this description. How can I tell the direction of the collision? What does the return value actually contain? How would I implement this collision for two Pygame Sprites with images and transparency?

Is there a more in-depth explanation (preferably with sample code) anywhere? I can't find anything more detailed than the documentation.


1 Answer 1


Returns the number of overlapping 'pixels'.

Let's see an example with a sprite collision of 2 sprites 3x3 (black and white)

Sprites colling on pixel (3,3) from black and (1,1) from white
Sprites colling on pixel (3,3) from black and (1,1) from white

Now, how pygame docs suggests, lets calculate the gradient of the overlap area with

dx = Mask.overlap_area(othermask,(x+1,y)) - Mask.overlap_area(othermask,(x-1,y))  
dy = Mask.overlap_area(othermask,(x,y+1)) - Mask.overlap_area(othermask,(x,y-1))

One by one:
Mask.overlap_area(othermask,(x+1,y)) = 0
Mask.overlap_area(othermask,(x-1,y)) = 2
Mask.overlap_area(othermask,(x,y+1)) = 2
Mask.overlap_area(othermask,(x,y-1)) = 0

dx = 0 - 2 = -2
dy = 2 - 0 = 2
(-2,2) indicates that the collision came from left (dx < 0) and up (dy > 0) of othermask

However this is not a very good way to determine the direction of collision. Pygame implements masks using Bitmask 1.7 (a pixel-perfect collision detection library) which, although very fast, may be redundant if your sprites have a common form (and you can detect the direction of the collision simply taking the difference of the coordinates)


You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .