How to make mask collision detection less laggy in python pygame

Viewed 186

Im trying to make a collision detection system for a game im making. This section of code works fine when I am detecting collisions when the objects are smaller, but now once I make a mask of a moon which can be up to 1000 pixels in diameter it starts to lag my computer. Ive tried to make a 2nd image of the outline of the moon to use to detect the collisions but upon further testing it would still detect collisions while in the middle of the outline (in the transparent parts of the image) and did not help the lag. I also tried to make the outline image less pixels but keeping the same size. The images move down the screen as a ship moves across the screen to dodge them. I need pixel perfect collisions If someone could tell me how to reduce lag, or some other way of detecting if my ship is within the circle that would be a big help :)

for i in range(numMoon):
    moonRect = pygame.Rect(moonX[i], moonY[i], int(100*moonScale[i]), int(100*moonScale[i]))
    if moonRect.colliderect(shipRect):
        moonMask = pygame.mask.from_surface(moon)
        offset_x = shipRect.x - moonRect.x
        offset_y = shipRect.y - moonRect.y
        crash = moonMask.overlap(shipMask, (offset_x, offset_y))
        if crash:
            print('moon')
1 Answers

Creating a Mask from a Surface is an expensive operation. Do not generate the pygame.mask in the loop. Create the mask during initialization directly after loading the image:

moon = pygame.image.load(...)
moonMask = pygame.mask.from_surface(moon)

Use the pre-generated mask

for i in range(numMoon):
    moonRect = pygame.Rect(moonX[i], moonY[i], int(100*moonScale[i]), int(100*moonScale[i]))
    if moonRect.colliderect(shipRect):
         offset_x = shipRect.x - moonRect.x
         offset_y = shipRect.y - moonRect.y
         crash = moonMask.overlap(shipMask, (offset_x, offset_y))
         if crash:
             print('moon')
Related