首页 > 解决方案 > Pygame - 精灵组运动不起作用

问题描述

我目前正在尝试对太空入侵者克隆进行编程。我创建了一个具有多个属性的“Invaders”-Class,并为我所有的敌方入侵者创建了一个精灵组。

class Invader(pygame.sprite.Sprite):
    def __init__(self, settings, picture, x, y):
        super().__init__()
        self.settings = settings
        self.x = x
        self.y = y
        self.image = pygame.image.load(os.path.join(self.settings.imagepath, picture)).convert_alpha()
        self.image = pygame.transform.scale(self.image, (63,38))
        self.rect = self.image.get_rect()
        self.rect.center = [self.x, self.y]

    def update(self):
        direction_change = False
        print(direction_change)
        if self.rect.x > 800:
            direction_change = True
        else:
            direction_change = False
        if direction_change == False:
            self.rect.x += 1
        if direction_change == True:
            self.rect.x -= 1

使用更新功能,我移动精灵组。但是当它移动到一个特定的点时,所有的精灵都会聚集在一起,它看起来像这样:

我的问题

有没有办法像单个对象一样移动组?

标签: pythonpygame

解决方案


移动方向必须是类的属性Invader如果Sprite位于窗口的左侧或右侧,则更改方向:

class Invader(pygame.sprite.Sprite):
    def __init__(self, settings, picture, x, y):
        super().__init__()
        self.settings = settings
        self.x = x
        self.y = y
        self.image = pygame.image.load(os.path.join(self.settings.imagepath, picture)).convert_alpha()
        self.image = pygame.transform.scale(self.image, (63,38))
        self.rect = self.image.get_rect()
        self.rect.center = [self.x, self.y]

        self.direction = 1 # <---

    def update(self):
        if self.rect.right >= 800:
            self.direction = -1
        if self.rect.left <= 0:
            self.direction = 1
        self.rect.x += self.direction

推荐阅读