问题描述
我正在尝试使用 pygame 编写平台游戏。 我曾尝试为我的角色添加空闲动画,但它似乎总是与我运行的其他动画重叠。
def update(self):
dx = 0
dy = 0
walk_cooldown = 1
#get keypresses
key = pygame.key.get_pressed()
if key[pygame.K_SPACE] and self.jumped == False:
self.vel_y= -15
self.jumped =True
if key[pygame.K_SPACE] == False:
self.jumped = False
if key[pygame.K_LEFT]:
dx -= 10
self.counter += 1
self.direction = -1
if key[pygame.K_RIGHT]:
dx += 10
self.counter += 1
self.direction = 1
if key[pygame.K_LEFT] == False and key[pygame.K_RIGHT] == False:
self.counter = 0
self.index = 0
if self.direction == 1:
self.image = self.images_right[self.index]
if self.direction == -1:
self.image = self.images_left[self.index]
#handle animation
if self.counter > walk_cooldown:
self.counter = 0
self.index += 1
if self.index >= len(self.images_right):
self.index = 0
if self.direction == 1:
self.image = self.images_right[self.index]
if self.direction == -1:
self.image = self.images_left[self.index]
我应该添加它们的最佳方式是什么?我在后台准备好了动画的所有图像,我的主要问题是试图让它们在正确的时间工作。我还需要添加跳跃动画,这对我来说似乎也是一个问题。
任何建议都会有所帮助, 谢谢:)
解决方法
每当我编写游戏程序时,我通常都会创建一个 is_walking
变量,当玩家空闲时该变量为 false,而当玩家走路时该变量为 true。然后你可以修改部分代码做如下操作:
if key[pygame.K_LEFT] == False and key[pygame.K_RIGHT] == False and not (is_walking):
self.counter = 0
self.index = 0
if self.direction == 1:
self.image = self.images_right[self.index]
if self.direction == -1:
self.image = self.images_left[self.index]
这将使您的代码达到仅在您不走路时执行空闲动画的程度,反之亦然。