Part4:Jump with State Machine(P31)
1:效果和操作
基本操作:添加新脚本playerGroundState,playerAirState,playerJumpState,添加新动画playerjump和playerfall,添加新动画参数yVelovity,jump,生成动画混合树用于控制player跳跃和下落状态转变
基本思路:当按下空格键后调用stateMachine.ChangeState(player.jumpState)进入jumpstate,并且根据player.jumpForce的高度跳跃,当往上跳时,velocity为正,保持jumpstate,只有当速度为负,即往下掉时转化为airstate(与playerfall状态对应),并且在起跳到落地这个过程,rb.velocity.y是由0➡️1➡️-1➡️0变化的,将其赋予给yvelocity即可完成由playerjump动画和playerfall动画之间的转变
2:代码改变
//新增PlayerJumpState
public class PlayerJumpState : PlayerState
{
public PlayerJumpState(Player _player, PlayerStateMachine _stateMachine, string _animBoolName) : base(_player, _stateMachine, _animBoolName)
{
}
public override void Enter()
{
base.Enter();
rb.velocity = new Vector2(rb.velocity.x, player.jumpForce);//改变y轴值,用于表示跳跃效果
}
public override void Update()
{
base.Update();
if (rb.velocity.y < 0)//jump时velocity为正,下落时velocity为负
{
stateMachine.ChangeState(player.airState);
}
}
public override void Exit()
{
base.Exit();
}
}
//新增PlayerAirState
public class PlayerAirState : PlayerState
{
public PlayerAirState(Player _player, PlayerStateMachine _stateMachine, string _animBoolName) : base(_player, _stateMachine, _animBoolName)
{
}
public override void Enter()
{
base.Enter();
}
public override void Update()
{
base.Update();
if (rb.velocity.y == 0)
{
stateMachine.ChangeState(player.idleState);
}
}
public override void Exit()
{
base.Exit();
}
}
//新增PlayerGroundState
//用于检测是否在地面上,idle和move状态必须于地面接触才可以进行
public class PlayerGroundState : PlayerState
{
public PlayerGroundState(Player _player, PlayerStateMachine _stateMachine, string _animBoolName) : base(_player, _stateMachine, _animBoolName)
{
}
public override void Enter()
{
base.Enter();
}
public override void Update()
{
base.Update();
if (Input.GetKeyDown(KeyCode.Space))
{
stateMachine.ChangeState(player.jumpState);
}//空格切换为跳跃状态
}
public override void Exit()
{
base.Exit();
}
}
//Player新增代码
public PlayerJumpState jumpState { get; private set; }
public PlayerAirState airState { get; private set; }
private void Awake()
{
stateMachine = new PlayerStateMachine();
//通过构造函数,在构造时传递信息
idleState = new PlayerIdleState(this, stateMachine, "Idle");
moveState = new PlayerMoveState(this, stateMachine, "Move");
jumpState = new PlayerJumpState(this, stateMachine, "Jump");
airState = new PlayerAirState(this, stateMachine, "Jump");
//因为airstate和jumpstate都在空中进行,所以animBoolName统一为Jump即可
}
//PlayerState新增代码
public virtual void Update()
{
player.anim.SetFloat("yVelocity", rb.velocity.y);//混合树中,接近-1播放fall动画,接近1播放jump动画
}
3.图示