![](/img/trans.png)
[英]Having problems creating an animation from a sprite sheet in pygame
[英]pygame animation sprite sheet
我想使用精靈表在 pygame 中創建一個自上而下的 RPG。
例如,我希望能夠按空格進行攻擊,這會觸發攻擊動畫,然后恢復正常
import pygame
from pygame.locals import *
pygame.init()
image = pygame.image.load("sprite_sheet.png")
clock = pygame.time.Clock()
screen = pygame.display.set_mode((400, 250))
class Player(pygame.sprite.Sprite):
def __init__(self):
super().__init__()
self.current_animation = 0
self.max_animation = 5
self.animation_cooldown = 150
self.last_animation = pygame.time.get_ticks()
self.status = {"prev": "standing",
"now": "standing"}
def animate_attack(self):
time_now = pygame.time.get_ticks()
if time_now - self.last_animation >= self.animation_cooldown:
self.last_animation = pygame.time.get_ticks()
if self.current_animation == self.max_animation:
self.current_animation = 0
joshua.status["now"] = joshua.status["prev"]
else:
self.current_animation += 1
joshua = Player()
while True:
screen.fill(0)
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
joshua.status["prev"] = joshua.status["now"]
joshua.status["now"] = "attacking"
if joshua.status["now"] == "attacking":
joshua.animate_attack()
screen.blit(image, (0, 0), (joshua.current_animation * 64, 0, 64, 64))
pygame.display.flip()
clock.tick(60)
上面的代碼是我所擁有的。 如果我按空格一次,它會通過動畫並停止,但如果我雙擊空格,它會循環播放,因為它是如何編程的。
求動畫方面的幫助,謝謝
問題是由第二次按下空格時的以下調用引起的:
joshua.status["prev"] = joshua.status["now"]
這將“prev”和“now”狀態都設置為“attacking”。 因此,當在animate_attack()
方法中重置狀態時,它將保持“攻擊”狀態:
joshua.status["now"] = joshua.status["prev"]
作為快速修復,請確保僅在尚未設置狀態時更改狀態:
if event.key == pygame.K_SPACE:
if not joshua.status["now"] == "attacking":
joshua.status["prev"] = joshua.status["now"]
joshua.status["now"] = "attacking"
作為更好的解決方法,您應該封裝狀態,以便只有 Player 類處理自己的狀態,例如:
class Player():
def __init__(self):
self.current_animation = 0
self.max_animation = 5
self.animation_cooldown = 150
self.last_animation = pygame.time.get_ticks()
self.status = "standing" # Simplified state
def attack(self):
self.status = "attacking"
def animate_attack(self):
if self.status == "attacking":
time_now = pygame.time.get_ticks()
if time_now - self.last_animation >= self.animation_cooldown:
self.last_animation = pygame.time.get_ticks()
if self.current_animation == self.max_animation:
self.current_animation = 0
self.status = "standing" # Reset state
else:
self.current_animation += 1
這樣,就不需要知道類之外的任何狀態:
while True:
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
joshua.attack()
joshua.animate_attack()
screen.fill(0)
screen.blit(image, (0, 0), (joshua.current_animation * 64, 0, 64, 64))
pygame.display.flip()
clock.tick(60)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.