步行周期未在游戏中结束



我在pygame中制作了一个行走动画。我让它开始朝前,然后如果你移动,动画会向左或向右切换,这取决于你移动的方式。但当我切换回不移动时,动画不会变回。

def animate(self):
now = pg.time.get_ticks()
if self.vel.x != 0:
self.walking = True
else:
self.walking = False
# Show walk animation
if self.walking:
if now - self.last_update > 200:
self.last_update = now
self.current_frame = (self.current_frame + 1) % len(self.walk_frames_l)
bottom = self.rect.bottom
if self.vel.x > 0:
self.image = self.walk_frames_r[self.current_frame]
else:
self.image = self.walk_frames_l[self.current_frame]
self.rect = self.image.get_rect()
self.rect.bottom = bottom
# Show idle animation
if not self.jumping and not self.walking:
if now - self.last_update > 350:
self.last_update = now
self.current_frame = (self.current_frame + 1) % len(self.standing_frames)
bottom = self.rect.bottom
self.image = self.standing_frames[self.current_frame]
self.rect = self.image.get_rect()
self.rect.bottom = bottom

我发现它没有停止的原因是与程序另一部分的运动逻辑有关,self.vel.x永远不会是0,只是非常接近它。我通过修复了它

if (self.vel.x // 1) != 0:

这使得如果电平为0.001,那么它将仅为0。如果我向右移动,这是有效的,但如果我向左移动,它不会切换回来。有人知道为什么吗?谢谢

如果你向左走,你的速度是负的。楼层划分(//(总是向下取整。这意味着,如果你的速度是-0.001,它将四舍五入到-1,而不是0。您可以通过在if之前执行print(self.vel.x // 1)来确认这一点。

解决方案是比较速度的绝对值。您可以通过执行abs(self.vel.x)来获得绝对值。

最新更新