首页 > 解决方案 > 步行周期不会在 pygame 中结束

问题描述

我在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:

这样一来,如果 vel 为 0.001,那么它将为 0。如果我向右移动,这会起作用,但如果我向左移动,它不会切换回来。有谁知道为什么?谢谢。

标签: pythonpygame

解决方案


如果你向左走,你的速度是负的。楼层除法 ( //) 总是向下取整。这意味着如果您的速度为 -0.001,它将向下舍入为 -1,而不是 0。您可以通过print(self.vel.x // 1)if.

解决方案是改为比较速度的绝对值。你可以通过做得到绝对值abs(self.vel.x)


推荐阅读