pygame-KidsCanCode系列jumpy-part11-角色动画(下)

2023-03-10,,

接上节继续,上节并没有处理向左走、向右走的动画效果,这节补上,看似很简单,但是有一些细节还是要注意:

    def jump(self):
hits = pg.sprite.spritecollide(self, self.game.platforms, False)
if hits:
self.vel.y = -PLAYER_JUMP
# 水平方向未走动时,才认为是向上跳跃状态
# (否则,如果向上跳时,同时按左右方向键,不会切换到向左或向右的转向动画)
if abs(self.vel.x) < 0.5:
self.jumping = True

首先,因为向左、向右走时,视觉上要能体现出转身的效果,所以在切换jumping状态时,就要考虑到这一点,另外由于我们之前加入了摩擦力,不管是x,还是y方向,减速的递减到最后趋于静止的阶段,都是不断靠近0(如果没有特殊处理的话,会在0左右的极小值摆动),因为判断速度是否为0,最好是abs取绝对值,然后跟一个较小的值,比如0.5比较,这样比较靠谱。

类似的,在animation函数中,也会考虑到这些细节,参考下面的代码:

     def animate(self):
now = pg.time.get_ticks() if self.vel.x != 0:
self.walking = True
else:
self.walking = False # 如果垂直方向静止,或水平方向有走动时,认为向上跳跃状态结束
if abs(self.vel.y) < 0.5 or abs(self.vel.x) > 0.5:
self.jumping = False if self.jumping:
self.image = self.jump_frame
# 下面的不再需要了,否则左右走动时,会变成站立状态
# else:
# self.image = self.standing_frames[0] # 水平向左/向右走的动画处理
if self.walking:
if now - self.last_update > 150:
self.last_update = now
self.current_frame += 1
bottom = self.rect.bottom
# 向左
if self.vel.x < 0:
self.image = self.walking_frames_left[self.current_frame % len(self.walking_frames_left)]
elif self.vel.x > 0:
# 向右
self.image = self.walking_frames_right[self.current_frame % len(self.walking_frames_right)]
self.rect = self.image.get_rect()
self.rect.bottom = bottom if not self.jumping and not self.walking:
if now - self.last_update > 200:
self.last_update = now
self.current_frame += 1
bottom = self.rect.bottom
self.image = self.standing_frames[self.current_frame % len(self.standing_frames)]
self.rect = self.image.get_rect()
self.rect.bottom = bottom

最终效果:

pygame-KidsCanCode系列jumpy-part11-角色动画(下)的相关教程结束。

《pygame-KidsCanCode系列jumpy-part11-角色动画(下).doc》

下载本文的Word格式文档,以方便收藏与打印。