前言
上一节我们实现了英雄角色的左右移动及跳跃功能,但是只有一张单一的图片,英雄无法产生更生动的形象。所以本节我们将会在人物运动的过程中为其添加动画效果。
Demo演示
我们先来看下本节的效果:
python使用pygame开发游戏系列之精灵动画的实现。
代码如下(player_animation.py):
import json
import pygame
class Player(object):
"""player对象"""
def __init__(self):
self.player_img = "zombie.png"
self.all_frames = self.load_frames_from_sheet()
self.rect = self.all_frames.get("left").get("idle")[0].get_rect()
self.rect.midbottom = (100, screen_height - 135)
self.vel_y = 0
self.current_frame = 0
self.jumped = False
self.direction = 1 # 1:右 -1:左
self.dir_frames = []
self.frames = []
self.state = 'idle'
self.is_attack = False
self.last_updated = 0
self.current_image = self.all_frames.get("left").get("idle")[0]
def handle_state(self):
"""根据状态决定行为"""
if self.direction == -1: # 根据方向选择朝向不同的序列图片
self.dir_frames = self.all_frames.get("left")
else:
self.dir_frames = self.all_frames.get("right")
if self.state == 'idle':
self.frames = self.dir_frames.get("idle")
elif self.state == "run":
self.frames = self.dir_frames.get("run")
elif self.state == "walk":
self.frames = self.dir_frames.get("walk")
elif self.state == "jump":
self.frames = self.dir_frames.get("jump")
elif self.state == "fall":
self.frames = self.dir_frames.get("fall")
elif self.state == "attack":
self.frames = self.dir_frames.get("attack")
def