簡體   English   中英

動畫精靈的問題(Pygame)

[英]Trouble animating sprites (Pygame)

我正在使用 pygame 開展一個學校項目,不幸的是在動畫我的精靈時遇到了麻煩,或者更具體地說,將精靈從一個更改為另一個,我不確定如何去做。 目前,我的飛船精靈和背景精靈有一個 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()

這具有左/右/上/下的基本運動。 我想要做的是讓我的 StarShip object 在變量 starship_1、starship_2、starship_3(其中包含我的星艦的 3 個精靈)之間不斷變化,所以看起來星艦正在移動。

我的精靈看起來像這樣:

星艦1

星艦2

星艦3

如您所見,這些精靈之間的區別在於引擎着火。 我將如何每 1 秒在這 3 個精靈之間進行切換?

僅供參考:當程序啟動時,會出現以下內容: 開機畫面

謝謝!

有 2 個部分可以實現此效果。

  1. 創建一個 function 來更改精靈的圖像。 (簡單的任務)
  2. 每 x 秒定期調用上述 function。 (中級任務)

第 1 步。您可以通過使用下一張圖像設置/加載 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM