Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to make a `Enemy` disappear when he faces with `Player`?

I made a few hearts for Player. When he faces with Enemy, Enemy won’t dissappear, so he might get from my sprite from 1 to 3 hearts instead 1. I tried to use the function self.kill(), however, it wasn’t helped. What I have to do?

class Enemy(pygame.sprite.Sprite):
    def __init__(self):
        super(Enemy, self).__init__()
        self.images = []
        self.images.append(pictures_mouse[0])
        self.images.append(pictures_mouse[1])
        self.images.append(pictures_mouse[2])
        self.images.append(pictures_mouse[3])
        self.index = 0
        self.image = self.images[self.index]
        self.rect = self.image.get_rect()
        #[...]
    def update(self):
        self.rect.move_ip(-2, 0)
        if self.rect.right <= 0:
            self.kill()
#[...]        
enemy = Enemy()
enemies = pygame.sprite.Group()
running = True
while running:
    clock.tick(FPS)
    for event in pygame.event.get():
         elif event.type == ADDENEMY:
            new_enemy = Enemy()
            enemies.add(new_enemy)
            all_sprites.add(new_enemy)
#[...]
    hits_4 = pygame.sprite.spritecollide(player, enemies, False)
        if hits_4:
             health -= 1
             if health == 0:
                 running = False

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

If you want to kill the enemies, that collide with the player you have to set the doKill argument of pygame.sprite.spritecollide:

hits_4 = pygame.sprite.spritecollide(player, enemies, False)

hits_4 = pygame.sprite.spritecollide(player, enemies, True)

Note, pygame.sprite.spritecollide returns a list containing all Sprites in a Group colliding with the Sptrit. Therefore you can also kill the enemies manually:

hits_4 = pygame.sprite.spritecollide(player, enemies, False)
for hit_enemy in hits_4:
    
    hit_enemy.kill()
    
    health -= 1
    if health == 0:
        running = False
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading