1

I'm trying to make multiple sprites follow the same algorithm that follows the main player. This is my code for my Sprite

class Zombie(pygame.sprite.Sprite):
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.Surface((10, 10))
        self.image.fill((250, 0, 0))
        self.rect = self.image.get_rect()
        self.rect.x = random.randrange(0, horizon - self.rect.width)
        self.rect.y = random.randrange(0, -100, -100)
        self.vel = random.randrange(5, 10)

    def update(self):
        # find normalized direction vector (dx, dy) between enemy and player
        dx, dy = player.rect.x - zombie.rect.x, player.rect.y - zombie.rect.y
        dist = math.hypot(dx, dy)
        dx, dy = dx / dist, dy / dist
        # move along this normalized vector towards the player at current speed
        zombie.rect.x += dx * zombie.vel
        zombie.rect.y += dy * zombie.vel

And this is my code for making multiple sprites

all_sprites = pygame.sprite.Group()
mobs = pygame.sprite.Group()
player = Player()
zombie = Zombie()
all_sprites.add(player)
for i in range(8):
    z = Zombie()
    all_sprites.add(z)
    mobs.add(z)

What happens is that only one of the sprites starts to follow the main player. How would I make each sprite follow the same code?

much thanks c;

Rabbid76
  • 202,892
  • 27
  • 131
  • 174
Miffuine
  • 31
  • 2

1 Answers1

1

Replace zombie. with self. in the update method:

class Zombie(pygame.sprite.Sprite):
    # [...]

    def update(self):
        # find normalized direction vector (dx, dy) between enemy and player
        dx, dy = player.rect.x - self.rect.x, player.rect.y - self.rect.y
        dist = math.hypot(dx, dy)
        dx, dy = dx / dist, dy / dist
        # move along this normalized vector towards the player at current speed
        self.rect.x += dx * self.vel
        self.rect.y += dy * self.vel
Rabbid76
  • 202,892
  • 27
  • 131
  • 174