Pygame图像动画循环未正确循环

时间:2017-06-08 22:22:29

标签: python pygame python-3.6

我有一个小动画循环,可以快速循环显示图像。我们的目标是让它保持恒定和流畅,但我似乎正在遇到一个问题,图像显示一秒钟并保持在第一帧。

以下代码来自整个播放器类,其中包含动画:

class Ship(pygame.sprite.Sprite):

    change_x = 0

    delay = 0
    frame = 1

    def __init__(self):
        pygame.sprite.Sprite.__init__(self)

        self.image = PlayerShip0.convert_alpha()

        self.rect = self.image.get_rect()

        self.rect.x = SCREEN_X / 2 - 100
        self.rect.y = SCREEN_Y - 40

    def move(self, speed):
        self.change_x = speed

    def stop(self):
        self.change_x = 0

    def update(self, screen):
        self.rect.x += self.change_x

        if self.rect.x < 0:
            self.rect.x = 0
        elif self.rect.right > SCREEN_X:
            self.rect.x -= 3

        self.delay += 1
        if self.delay >= 50:
            if self.frame == 1:
                self.image = PlayerShip0.convert_alpha()
                self.frame = 2
                self.delay = 1
            if self.frame == 2:
                self.image = PlayerShip1.convert_alpha()
                self.frame = 3
                self.delay = 1
            if self.frame == 3:
                self.image = PlayerShip2.convert_alpha()
                self.frame = 1
                self.delay = 1

        print(self.frame)

        screen.blit(self.image,self.rect)

1 个答案:

答案 0 :(得分:1)

而不是

        if self.frame == 1:
            self.image = PlayerShip0.convert_alpha()
            self.frame = 2
            self.delay = 1
        if self.frame == 2:
            self.image = PlayerShip1.convert_alpha()
            self.frame = 3
            self.delay = 1
        if self.frame == 3:
            self.image = PlayerShip2.convert_alpha()
            self.frame = 1
            self.delay = 1

使用

        if self.frame == 1:
            self.image = PlayerShip0.convert_alpha()
            self.frame = 2
            self.delay = 1
        elif self.frame == 2:
            self.image = PlayerShip1.convert_alpha()
            self.frame = 3
            self.delay = 1
        elif self.frame == 3:
            self.image = PlayerShip2.convert_alpha()
            self.frame = 1
            self.delay = 1

否则,您会在第一个self.frame块中将2设置为if,而第二个if块会立即将其设置为3,第三个if块实体的条件,依此类推。