The most advance sprites overlapping detection method from Pygame

When it comes to sprites overlap detection rectangle detection method is not as accurate as circle detection method and circle detection method is less accurate than the bitmasks detection method. According to the Pygame wiki page this is what the bitmasks method does and what it needs to detect the overlapping between two sprites.

Tests for collision between two sprites, by testing if their bitmasks overlap. If the sprites have a “mask” attribute, that is used as the mask, otherwise a mask is created from the sprite image. Intended to be passed as a collided callback function to the *collide functions. Sprites must have a “rect” and an optional “mask” attribute.

You should consider creating a mask for your sprite at load time if you are going to check collisions many times. This will increase the performance, otherwise this can be an expensive function because it will create the masks each time you check for collisions.

If you want to create the mask attribute then all you need is this line of command

sprite.mask = pygame.mask.from_surface(sprite.image)

where sprite.image is the surface of the game sprite. Then you will use this command to check the overlapping between two sprites

pygame.sprite.collide_mask(left_sprite, right_sprite)

where the left_sprite and the right_sprite is the sprite object you wish to check for overlapping, the method above will return the first point on the mask where the overlapping occurs or None if there was no overlapping.

One thing you need to take note of is if you are using the spritesheet to animate the sprite object instead of a single image then you should use the circle detection method instead because you will need to create different sprite surface object as well as different mask attribute which is really against the game’s performance if you go with the bitmask method above. Otherwise use the bitmasks method will result in the most precise overlapping detection as compared to the rectangle and the circle detection method!

Leave a Reply

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