Pygame: Detecting Collisions Cheat Sheet

You can detect when a single object collides with any member of a group. You can also detect when any member of one group collides with a member of another group.

Collisions between a single object and a group

The spritecollideany() function takes an object and a group, and returns True if the object overlaps with any member of the group

if pg.sprite.spritecollideany(ship, aliens):
    ships_left -= 1

Collisions between two groups

The sprite.groupcollide() function takes two groups, and two booleans. The function returns a dictionary containing information about the members that have collided. The booleans tell Pygame whether to delete the members of either group that have collided.

collisions = pg.sprite.groupcollide(bullets, aliens, True, True)
score += len(collisions) * alien_point_value

Leave a Reply

Your email address will not be published. Required fields are marked *