# How to use collision masks and overlap_area in pygame?

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.

overlap_area()
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

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))


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)