Skip to content
Advertisement

Pygame collision with masks

I have made a putt-putt game and now I want to add a slanted wall type. Because of this, I need to use masks for the collision (until now I have just used rects). I have spent hours learning about masks and trying to figure out why my code won’t work. There are no errors, the collision just isn’t detected.

I have simplified my code down to something much smaller just as a way for me to test it efficiently. From everything I’ve seen this seems like it should work, but it doesnt. Here it is:

JavaScript

Advertisement

Answer

The offset parameter of the method overlap() is the relative position of the othermask in relation to the pygame.mask.Mask object.
So the offset is calculated by subtracting the coordinates of slant from the coordinates of ball:

offset_x, offset_y = (slant.rect.x - ball.rect.x), (slant.rect.y - ball.rect.y)

JavaScript

When you create the mask images, then I recommend to ensure that the image has per pixel alpha format by calling .convert_alpha():

JavaScript
JavaScript

Minimal example: repl.it/@Rabbid76/PyGame-SurfaceMaskIntersect

See also: Mask

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement