Enemy状态以及切换图
程序架构
public interface IState
{
void OnEnter( ) ; //进入状态时
void OnUpdate( ) ; //执行状态时
void OnExit( ) ; //退出状态时
}
public class IdleState : IState
{
private FSM manager;
private Parameter parameter;
public float timer;
public IdleState( FSM manager)
{
this.manager = manager;
this.parameter = manager.parameter;
}
public void OnEnter ( )
{
parameter.animator.Play( "Idle" ) ;
}
public void OnUpdate ( )
{
timer += Time.deltaTime; //加上上一帧经过的时间
if( parameter.target != null &&
parameter.target.position.x >= parameter.chasePoints[ 0 ] .position.x &&
parameter.target.position.x <= parameter.chasePoints[ 1 ] .position.x)
{
manager.TransitionState( StateType.React) ; //发现敌人,切换为反应状态
}
if( timer >= parameter.idleTime) //达到状态机设置好的时间
{
manager.TransitionState( StateType.Patrol) ; //转换为巡逻状态
}
}
public void OnExit ( )
{
timer = 0 ; //退出时计时器清0
}
}
.. .
public enum StateType
{
Idle, Patrol, Chase, React, Attack, Hit, Death
}
public class FSM : MonoBehaviour
{
private IState currentState; //当前状态
private Dictionary< StateType, IState> states = new Dictionary< StateType, IState> ( ) ; //注册状态字典
public Parameter parameter;
void Start ( )
{
//注册状态
states.Add( StateType.Idle, new IdleState( this)) ;
states.Add( StateType.Patrol, new PatrolState( this)) ;
states.Add( StateType.Chase, new ChaseState( this)) ;
states.Add( StateType.React, new ReactState( this)) ;
states.Add( StateType.Attack, new AttackState( this)) ;
states.Add( StateType.Hit, new HitState( this)) ;
states.Add( StateType.Death, new DeathState( this)) ;
TransitionState( StateType.Idle) ; //设置初始状态
parameter.animator = transform.GetComponent< Animator> ( ) ; //设置动画控制器
}
void Update ( )
{
currentState.OnUpdate( ) ; //在当前状态中,持续执行当前的函数
}
public void TransitionState( StateType type )
{
if ( currentState != null)
currentState.OnExit( ) ; //退出当前状态
currentState = states[ type] ;
currentState.OnEnter( ) ; //进入新状态
}
.. .
}