怪物状态机基类,用于继承,定义方法
//状态机基类
public class StateBase
{
protected FsmManager fsm;
public StateBase(FsmManager fsmManager)
{
this.fsm=fsmManager;
}
//进入
public virtual void OnEnter(){};
//退出
public virtual void OnExit(){};
//Update
public virtual void OnUpdate(){};
//改变
public virtual void OnChange(){};
}
状态机管理类 改变状态机状态,调用方法
/// <summary>
/// 状态
/// </summary
public enum StateType
{
Patorl,//巡逻
Chase,//追击
Attack//攻击
}
/// <summary>
/// 状态管理类
/// </summary
public class FSMMagaer
{
Dictionary<StateType,StateBase> dic=new Dictionary<StateType,StateBase>
StateBase now_State;//当前状态
/// <summary>
/// 添加状态
/// </summary
public void AddState(StateType stateType,StateBase stateBase)
{
dic.Add(stateType,stateBase);
}
/// <summary>
/// 删除状态
/// </summary
public void RemoveState(StateType stateType)
{
dic.Add(stateType,stateBase);
}
public void UpdateState()
{
now_State.OnChange();
now_State.OnUpdate();
}
public void OnRunState(StateType statetype)
{
if(now_State!=null)
{
now_State.OnExit();
}
now_State=dic[statetype];
now_State.OnEnter();
}
}
状态的逻辑 重写状态机父类方法,显现状态的应用
/// <summary>
/// 巡逻
/// </summary>
public class Patorl : StateBase
{
Transform transform,fotetransform;
NavMeshAgent nav;
public Patorl(FSMMagaer fSMMagaer,Transform transform) : base(fSMMagaer)
{
this.transform = transform;
fotetransform = GameObject.FindGameObjectWithTag("Player").transform;
nav = transform.GetComponent<NavMeshAgent>();
}
public override void OnEnter()
{
base.OnEnter();
}
public override void OnExit()
{
base.OnExit();
}
//重写OnUpdate方法
public override void OnUpdate()
{
base.OnUpdate();
if (nav.remainingDistance<=0.5f)
{
nav.SetDestination(new Vector3(Random.Range(-20, 20), 0, Random.Range(-20, 20)));
}
}
//重写OnChange方法
public override void OnChange()
{
base.OnChange();
if (Vector3.Distance(transform.position,fotetransform.position)<=5)
{
fsm.OnRunState(StateType.Chase);
}
}
}
public class EnemyMove : MonoBehaviour
{
FSMMagaer contorller = new FSMMagaer();
public Slider slider;
void Start()
{
//添加状态
contorller.AddState(StateType.Patorl, new Patorl(contorller, transform));
contorller.AddState(StateType.Chase, new Chase(contorller, transform));
contorller.AddState(StateType.Attack, new Attack(contorller, transform));
contorller.OnRunState(StateType.Patorl);
}
void Update()
{
contorller.UpdateState();
}
}