Search code examples
pythonpygamecollision-detection

How to know if one of my bullet sprites collided with my enemy/boulder sprite? - pygame


I have a game where the player can shoot bullets in all 4 directions. I want to delete my boulder/enemy sprite when any one of my bullet sprite touchhes it. How do i go about doing this?

Relevant code-

Bullet sprite:

class Bullet(pygame.sprite.Sprite):

    def __init__(self, bulletdir1):
        super().__init__()
        self.bulletdir = bulletdir1
        self.image = pygame.Surface((30, 10))
        self.image.fill((195, 222, 18))
        if self.bulletdir == "N" or self.bulletdir == "S":
            self.image = pygame.transform.rotate(self.image, 90)
        else:
            pass
        self.rect = self.image.get_rect(
            center=(playerpos.x + 53, playerpos.y + 27))

    def update(self):
        if self.bulletdir == "N":
            self.rect.y -= 10
        if self.bulletdir == "S":
            self.rect.y += 10
        if self.bulletdir == "W":
            self.rect.x -= 10
        if self.bulletdir == "E":
            self.rect.x += 10
        if self.rect.y <= 0 or self.rect.y >= 600 or self.rect.x <= 0 or self.rect.x >= 998:
            self.kill()

boulder sprite:

class Boulder(pygame.sprite.Sprite):
    def __init__(self):
        super().__init__()
        self.image= pygame.image.load("PS/boulder.png")
        self.rect= self.image.get_rect(center=(100,100))
        if self.rect.colliderect()
boulder_grp.add(Boulder())

As of now, there is oly one static boulder on my screen, and the bullet sprites are being called/made when a specific key is being pressed


Solution

  • You have a boulder_grp Group and I assume that you have a bullet_grp Group. Use pygame.sprite.groupcollide and set the dokill1 and dokill2 attribute to destroy (_kill) the objects:

    All you need to do is to call pygame.sprite.groupcollide:

    pygame.sprite.groupcollide(boulder_grp, bullet_grp, True, True)
    

    See also How do I detect collision in pygame? and When I use pygame.sprite.spritecollide(), why does only the bullets disappear?.