Skip to content Skip to sidebar Skip to footer

How To Check Collision Of Mouse With Sprites In Pygame?

I replaced my mouse with a crosshair and I have some targets on the screen. When you shoot a target, it's supposed to disappear from the screen. How can I check if the CENTER of my

Solution 1:

Since the targets are circular, the collision can b detected by calculating the distance from the mouse pointer to the center of the target.

Compute the square of the Euclidean distance (dx*dx + dy*dy) from the mouse cursor to the center of the target. Test that the square of the distance is less than the square of the radius:

Pass the mouse position to the Crosshair.shoot. Go through the targets and kill a target when a collision is detected:

class Crosshair(pygame.sprite.Sprite):
    # [...]
    
    def shoot(self, mouse_pos):
        for target in target_group:
            dx = target.rect.centerx - mouse_pos[0]
            dy = target.rect.centery - mouse_pos[1]
            dist_sq = dx*dx + dy*dy
            radius = target.image.get_width() / 2
            if dist_sq < radius*radius:
                target.kill()
running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        if event.type == pygame.MOUSEBUTTONDOWN:
            crosshair.shoot(event.pos)            # <--- pass event.pos

    # [...]

An more elegant solution, however, is to use pygame.sprite.collide_circle(). This function can be passed to pygame.sprite.spritecollide() as a callback argument.
For this solution the pygame.sprite.Sprite objects must have an attribute radius:

class Crosshair(pygame.sprite.Sprite):
    def __init__(self, image):
        super().__init__()
        self.image = image
        self.rect = self.image.get_rect()
        self.radius = 1

    def update(self):
        self.rect.center = pygame.mouse.get_pos()
    
    def shoot(self, mouse_pos):
        self.rect.center = mouse_pos
        pygame.sprite.spritecollide(self, target_group, True, pygame.sprite.collide_circle)
class Target(pygame.sprite.Sprite):
    def __init__(self, image, x, y):
        super().__init__()
        self.image = image
        self.rect = self.image.get_rect()
        self.rect.center = (x, y)
        self.radius = self.rect.width // 2

Post a Comment for "How To Check Collision Of Mouse With Sprites In Pygame?"