在Pygame中单独移动精灵

时间:2018-11-17 22:46:15

标签: python pygame sprite

我正在尝试使多个精灵遵循与主要玩家相同的算法。 这是我的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

这是我制作多个精灵的代码

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)

发生的事情是,只有一个精灵开始跟随主玩家。 我该如何使每个精灵遵循相同的代码?

非常感谢c;

1 个答案:

答案 0 :(得分:0)

将更新方法中的 zombie. 替换为 self.

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