python - 步行周期不会在 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。如果我向右移动,这会起作用,但如果我向左移动,它不会切换回来。有谁知道为什么?谢谢。
解决方案
如果你向左走,你的速度是负的。楼层除法 ( //
) 总是向下取整。这意味着如果您的速度为 -0.001,它将向下舍入为 -1,而不是 0。您可以通过print(self.vel.x // 1)
在if
.
解决方案是改为比较速度的绝对值。你可以通过做得到绝对值abs(self.vel.x)
。
推荐阅读
- wordpress - wordpress 管理页面的菜单是空的
- c - 右位移将 1 添加到 C 中 unsigned int 的开头
- android - 如何重置计步器?
- python - 是否可以使用 python 在 sqlite3 中运行多个语句?
- javascript - '无法设置未定义的属性“innerHTML”' - 但它已定义
- vim - 根据模式匹配突出显示整行
- graph - GTFS 到图形的转换?
- sql-server - 如何让 SSIS 包动态选择所需的连接管理器?
- java - 是否可以使用通配符逻辑“*”通过 Apache Maven 目标和选项列出特定目录?
- visual-studio-code - VSCode 在打开某些文件时隐藏文件夹内容