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

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

    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函数中,也会考虑到这些细节,参考下面的代码:

 1     def animate(self):
 2         now = pg.time.get_ticks()
 3 
 4         if self.vel.x != 0:
 5             self.walking = True
 6         else:
 7             self.walking = False
 8 
 9         # 如果垂直方向静止,或水平方向有走动时,认为向上跳跃状态结束
10         if abs(self.vel.y) < 0.5 or abs(self.vel.x) > 0.5:
11             self.jumping = False
12 
13         if self.jumping:
14             self.image = self.jump_frame
15         # 下面的不再需要了,否则左右走动时,会变成站立状态
16         # else:
17         #     self.image = self.standing_frames[0]
18 
19         # 水平向左/向右走的动画处理
20         if self.walking:
21             if now - self.last_update > 150:
22                 self.last_update = now
23                 self.current_frame += 1
24                 bottom = self.rect.bottom
25                 # 向左
26                 if self.vel.x < 0:
27                     self.image = self.walking_frames_left[self.current_frame % len(self.walking_frames_left)]
28                 elif self.vel.x > 0:
29                     # 向右
30                     self.image = self.walking_frames_right[self.current_frame % len(self.walking_frames_right)]
31                 self.rect = self.image.get_rect()
32                 self.rect.bottom = bottom
33 
34         if not self.jumping and not self.walking:
35             if now - self.last_update > 200:
36                 self.last_update = now
37                 self.current_frame += 1
38                 bottom = self.rect.bottom
39                 self.image = self.standing_frames[self.current_frame % len(self.standing_frames)]
40                 self.rect = self.image.get_rect()
41                 self.rect.bottom = bottom

最终效果:

posted @ 2019-02-17 17:50  菩提树下的杨过  阅读(489)  评论(0编辑  收藏  举报