Collision between masks in pygame

The mask for the Terrain is never set. Crate a proper Terrain mask:

class Terrain(object):
    def __init__(self, x, y):
        self.x = x
        self.y = y
    
        maskSurf = pg.Surface((display_width, display_height)).convert_alpha()
        maskSurf.fill(0)
        pg.draw.rect(maskSurf, (160, 160, 160), (self.x, self.y, display_width, 500), 0)
        self.mask = pg.mask.from_surface(maskSurf)
        print(self.mask.count())
 
        # [...]

When using pygame.mask.Mask.overlap(), then you’ve to check the overlapping of the Spaceship and the Terrain, rather than the Terrain and the Spaceship.
Since the Terrain mask is a mask of the entire screen, the offset for the overlap() test is the position of the Spaceship:

def check_for_collisions():
    offset = (int(spaceship.x), int(spaceship.y))
    collide = terrain.mask.overlap(spaceship.mask, offset)
    print(offset, collide)
    return collide

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

See also: Mask

Leave a Comment