当我向上,向下,向左或向右走时,我想在我向那个方向走的时候播放3张图像。
player = pygame.image.load('data/down1.png')
playerX = 610
playerY = 350
while 1:
clock.tick(30)
for event in pygame.event.get():
if event.type == pygame.QUIT:
return
if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
return
if event.type == pygame.KEYDOWN and event.key == pygame.K_DOWN:
player = pygame.image.load('data/down1.png')
player = pygame.image.load('data/down2.png')
player = pygame.image.load('data/down3.png')
playerY = playerY + 5
screen.fill((0, 0, 0))
screen.blit(player, (playerX, playerY))
pygame.display.flip()
(这是我的代码btw的一部分) 那么有什么方法可以让我这样做,所以当我走下去时它就像一个走下来的图像的动画?
答案 0 :(得分:7)
您可以使用名称创建循环缓冲区。
images = ['data/down1.png','data/down2.png','data/down3.png']
然后更改计数器
...
if event.type == pygame.KEYDOWN and event.key == pygame.K_DOWN:
player = pygame.image.load(images[counter])
counter = (counter + 1) % len(images)
playerY = playerY + 5
...
按下按钮时会改变图像。
答案 1 :(得分:2)
TL; DR:你必须自己做动画
您在该代码中所做的只是加载3张图片,第3张图片正在显示,因为它是覆盖player
变量的最后一张图片。你需要设置一个动画循环,这很复杂,不幸的是在StackExchange回复范围之外。
这是一般性的想法,希望你能找到更完整的教程:
这是一个巨大的过度简化,所以随时准备好了解更多信息。这可能是一种非常低效的方式,但是你不应该担心优化,直到你需要(即你的游戏是滞后的)。祝你好运!
答案 2 :(得分:0)
这比你想象的要复杂得多。
您必须在列表中加载图像(不在一个变量player
中)
您需要变量walking = True
。
如果walking == True
,则显示列表中的下一张图片playerY = playerY + 1
在下一个循环中执行相同操作直到玩家移动到预期位置。然后是walking = False
。
我可以查看它但看起来更像是这样:
player_images = []
player_images.append( pygame.image.load('data/down1.png') )
player_images.append( pygame.image.load('data/down2.png') )
player_images.append( pygame.image.load('data/down3.png') )
player_current = 0
player = player_images[ player_current ]
playerX = 610
playerY = 350
walking = False
walking_steps = 0
while True:
# --- FPS ---
clock.tick(30)
# --- events ---
for event in pygame.event.get():
if event.type == pygame.QUIT:
return
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
return
elif event.key == pygame.K_DOWN:
walking = True
walking_steps = 5
# --- moves ---
if walking == True:
# here you need to check some counter
# if it is time for next step to walk slower
# but don't use `time.sleep()`
if walking_steps > 0:
player_current = (player_current + 1) % len(player_images)
player = player_images[ player_current ]
playerY = playerY + 1
walking_steps -= 1
else:
walking = False
# --- draws ---
screen.fill((0, 0, 0))
screen.blit(player, (playerX, playerY))
pygame.display.flip()