精灵动画问题 (Pygame)

Trouble animating sprites (Pygame)

我正在与 pygame 一起进行一个学校项目,不幸的是 运行 在为我的 sprite 设置动画时遇到了麻烦,或者更具体地说,将 sprite 从一个更改为另一个,我不确定关于如何去做。目前,我有一个 class 我的飞船精灵和背景精灵:

game_folder = os.path.dirname(__file__)
img_folder = os.path.join(game_folder, 'img')
space_background = pygame.image.load('background.png').convert()
starship_1 = pygame.image.load('starship2.png').convert()
starship_2 = pygame.image.load('starship3.png').convert()
starship_3 = pygame.image.load('starship4.png').convert()


class starship(pygame.sprite.Sprite):
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.transform.scale(starship_1, (150,150))
        self.image.set_colorkey(black)
        self.rect = self.image.get_rect()
        self.rect.center = (400, 400)

all_sprites = pygame.sprite.Group()
BackGround = background()
StarShip = starship()
all_sprites.add(BackGround)
all_sprites.add(StarShip)

我的 while 循环看起来像这样:

run = True

while run:
    pygame.time.delay(100)

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

    keys = pygame.key.get_pressed()
    
    if keys[pygame.K_LEFT] and StarShip.rect.x > 25:  
        StarShip.rect.x -= vel

    if keys[pygame.K_RIGHT] and StarShip.rect.x < 600:  
        StarShip.rect.x += vel

    if keys[pygame.K_UP] and StarShip.rect.y > 25: 
        StarShip.rect.y -= vel

    if keys[pygame.K_DOWN] and StarShip.rect.y < 600:
        StarShip.rect.y += vel

    
    win.fill((0,0,0))
    all_sprites.update()
    all_sprites.draw(win)
    pygame.display.update() 
    
pygame.quit()

这有left/right/up/down的基本动作。我想要做的是让我的 StarShip 对象在变量 starship_1、starship_2、starship_3 之间不断变化(其中包含我的星舰的 3 个精灵),所以看起来星舰是移动。

我的精灵看起来像这样:

如您所见,引擎点火是这些精灵之间的区别。我如何每 1 秒在这 3 个精灵之间切换?

仅供参考:当程序启动时,出现的是:

谢谢!

有2个部分可以实现这个效果。

  1. 创建一个函数来改变精灵的形象。 (简单的任务)
  2. 每隔 x 秒定期调用上述函数。 (中级任务)

第一步。 您可以通过 setting/loading 下一张图片的 self.image 变量来实现。

第 2 步

clock = pygame.time.Clock()

time_counter = 0
images = ['starship_1', 'starship_2', 'starship_3']
current_img_index = 0

while run:    
    # Your Code

    time_counter = clock.tick()

    # 1000 is milliseconds == 1 second. Change this as desired
    if time_counter > 1000:
        # Incrementing index to next image but reseting back to zero when it hits 3
        current_img_index = (current_img_index + 1) % 3 
        set_img_function(current_img_index) # Function you make in step 1

        # Reset the timer
        time_counter = 0

一个好的方法是完成第 1 步,然后将其绑定到按钮。测试它是否有效,然后继续执行步骤 2。

关于此代码中使用的函数以完全理解它们的一些很好的阅读是 here