Pygame - 精灵组运动不起作用

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


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

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

https://img1.mukewang.com/651297d80001cc5f06520511.jpg

有没有办法像移动单个物体一样移动该组?



回首忆惘然
浏览 50回答 1
1回答

撒科打诨

移动方向必须是该类的属性Invader。如果精灵位于窗口的左侧或右侧,则更改方向:class Invader(pygame.sprite.Sprite):&nbsp; &nbsp; def __init__(self, settings, picture, x, y):&nbsp; &nbsp; &nbsp; &nbsp; super().__init__()&nbsp; &nbsp; &nbsp; &nbsp; self.settings = settings&nbsp; &nbsp; &nbsp; &nbsp; self.x = x&nbsp; &nbsp; &nbsp; &nbsp; self.y = y&nbsp; &nbsp; &nbsp; &nbsp; self.image = pygame.image.load(os.path.join(self.settings.imagepath, picture)).convert_alpha()&nbsp; &nbsp; &nbsp; &nbsp; self.image = pygame.transform.scale(self.image, (63,38))&nbsp; &nbsp; &nbsp; &nbsp; self.rect = self.image.get_rect()&nbsp; &nbsp; &nbsp; &nbsp; self.rect.center = [self.x, self.y]&nbsp; &nbsp; &nbsp; &nbsp; self.direction = 1 # <---&nbsp; &nbsp; def update(self):&nbsp; &nbsp; &nbsp; &nbsp; if self.rect.right >= 800:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; self.direction = -1&nbsp; &nbsp; &nbsp; &nbsp; if self.rect.left <= 0:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; self.direction = 1&nbsp; &nbsp; &nbsp; &nbsp; self.rect.x += self.direction
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python