Unity3D自学笔记——有限状态机(二)角色行走控制

有限状态机(二)角色行走控制

创建State

public enum FSMStateType
{
    None,
    Default,
    Idle,
    Move,
}

Idle

public class IdleState : FSMState
{
    public override void Action(FSMBase fsm)
    {
        fsm.PlayAnimation(AnimationParameters.Idle);
    }

    public override void EnterState(FSMBase fsm)
    {

    }

    public override void ExitState(FSMBase fsm)
    {

    }

    public override void InitState()
    {
        this.StateType = FSMStateType.Idle;
    }
}

Move

public class MoveState : FSMState
{
    public override void Action(FSMBase fsm)
    {
        fsm.PlayAnimation(AnimationParameters.Move);
        fsm.Controller.Move();
    }

    public override void EnterState(FSMBase fsm)
    {

    }

    public override void ExitState(FSMBase fsm)
    {

    }

    public override void InitState()
    {
        this.StateType = FSMStateType.Move;
    }
}

创建Trigger

public enum FSMTriggerType
{
    CanBeMove,
    IsIdle,
}

是否移动

public class CanBeMoveTrigger : FSMTrigger
{
    public override void Init()
    {
        this.TriggerType = FSMTriggerType.CanBeMove;
    }

    protected override bool Evaluate(FSMBase fsm)
    {
        return Mathf.Abs(Input.GetAxis("Horizontal")) > 0.5 || Mathf.Abs(Input.GetAxis("Vertical")) > 0.5;
    }
}

是否静止

public class IsIdleTrigger : FSMTrigger
{    public override void Init()
    {
        this.TriggerType = FSMTriggerType.IsIdle;
    }

    protected override bool Evaluate(FSMBase fsm)
    {
        bool rst = Mathf.Abs(Input.GetAxis("Horizontal")) <= 0.5 && Mathf.Abs(Input.GetAxis("Vertical")) <= 0.5;
        return rst;
    }
}

创建角色的FSM

public class FSMPlayer : FSMBase
{
    public override void ConfigFSM()
    {
        IdleState idle = new IdleState();
        idle.AddTrigger(FSMTriggerType.CanBeMove, FSMStateType.Move);

        MoveState move = new MoveState();
        move.AddTrigger(FSMTriggerType.IsIdle, FSMStateType.Idle);

        AddState(idle);
        AddState(move);
    }
}

创建角色的动画播放管理类

public class PlayerAnimationManager : CharacterAnimationManager
{
}

将FSM和AnimationManager挂在角色预制体上

Unity3D自学笔记——有限状态机(二)角色行走控制_第1张图片

设置Animator

Unity3D自学笔记——有限状态机(二)角色行走控制_第2张图片

你可能感兴趣的:(Unity3D)