In the previous tutorial we are using the rectangle area of the sprite to detect the overlapping between two sprite objects but today we will use the circle area to detect the above mentioned event instead which is more accurate as compared to the rectangle detection method because we can simple adjust the radius of the circle accordingly to achieve the best affect!
In order to use the circle detection method we will need to include a new radius attribute in the GameSprite module which will now replace the rect attribute uses to detect the sprite overlapping event (you can still use the rect attribute if you want to but the outcome will be the same as the rectangle detection method).
Below is the only line of code we have to add in under def __init__(self, image, width, height) of GameSprite module.
#use to detect overlap self.radius = width/4
By providing the radius attribute and then set it to 1/4 of the sprite width we now don’t even need to recalculate the Rect object after each position update of the sprite and therefore we can comment out the below lines of code under detectCollide(self, right, player_draw_pos, enemy_draw_pos)
#self.rect = Rect(player_draw_pos.x, player_draw_pos.y, self.width, self.height) #right.rect = Rect(enemy_draw_pos.x, enemy_draw_pos.y, right.width, right.height)
Under the same method above we will now change the overlapping detection method from pygame.sprite.collide_rect(self, right) to pygame.sprite.collide_circle(self, right) and that is all we need.
Now if you run the main game module you will notice that the overlapping only occurs when the enemy get closed enough to the player as compared to the previous method where the enemy will be removed even it looks like the enemy is still some distance apart from the player.