-1

So once again I am trying to make a little shooting game where you have to dodge or shoot at enemies to win. The game is over once you get hit by an enemy and I managed to make that work. Yet my problem now is that I need a way to make it that once the enemy class and missiles class collide with each other they both disappear. But I couldn't figure a way to do that.

class Enemy(pg.sprite.Sprite):
    def __init__(self):
        super(Enemy, self).__init__()
        self.surf = pg.image.load("Enemy.png").convert()
        self.surf = pg.transform.smoothscale(self.surf, (75, 75))
        self.surf.set_colorkey((255, 255, 255), RLEACCEL)
        self.rect = self.surf.get_rect(center=(
                random.randint(SCREEN_WIDTH + 20, SCREEN_WIDTH + 100),
                random.randint(0, SCREEN_HEIGHT),
            )
        )
        self.speed = random.randint(5, 15)
    def update(self):
        self.rect.move_ip(-self.speed, 0)
        if self.rect.right < 0:
            self.kill()
class Missile(pg.sprite.Sprite):
    def __init__(self, pos):
        super(Missile, self).__init__()
        self.surf = pg.image.load("Missile.png").convert()
        self.surf = pg.transform.smoothscale(self.surf, (20, 20))
        self.surf.set_colorkey((0, 0, 0), RLEACCEL)
        self.rect = self.surf.get_rect(center=pos)
    def update(self):
        self.rect.move_ip(10, 0)
        if self.rect.right < 0:
            self.kill()
ModyDz
  • 115
  • 8

1 Answers1

2

Call pygame.sprite.Sprite.kill() on both objects when they collide. kill removes a sprite from all groups that contain it.

The collision can be detected with pygame.sprite.collide_rect(). I the following enemy is an instance of Enemy and missile is an instance of Missile:

if (pygame.sprite.collide_rect(enemy, missile):
    enemy.kill()
    missile.kill()

If you have a pygame.sprite.Group of missiles you can use pygame.sprite.spritecollide(). When the dokill argument is True, the colliding missile will be killed automatically:

if pygame.sprite.spritecollide(enemy, missiles, True):
    enemy.kill()

If you have Group of enemies and a Group of missiles, you can use pygame.sprite.groupcollide(). When either dokill1 or doKill2 is True, the corresponding object will be killed automatically:

pygame.sprite.groupcollide(enemies, missiles, True, True)
Rabbid76
  • 202,892
  • 27
  • 131
  • 174