public interface IState
{
void OnEnter();
void OnUpdate();
void OnExit();
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class IdleState : IState
{
private FSM manager;
private Parameter parameter;
private float timer;
public IdleState(FSM manager)
{
this.manager = manager;
this.parameter = manager.parameter;
}
public void OnEnter()
{
Debug.Log("WK_archer_01_idle_A");
parameter.animator.Play("WK_archer_01_idle_A");
}
public void OnExit()
{
timer = 0;
}
public void OnUpdate()
{
timer += Time.deltaTime;
if (timer >= parameter.idleTime)
{
manager.TransitionState(StateType.Patrol);
}
}
}
public class PatrolState : IState
{
private FSM manager;
private Parameter parameter;
private float timer;
private int patrolPosition = 0;
public PatrolState(FSM manager)
{
this.manager = manager;
this.parameter = manager.parameter;
}
public void OnEnter()
{
Debug.Log("WK_archer_02_walk");
parameter.animator.Play("WK_archer_02_walk");
}
public void OnUpdate()
{
manager.FlipTo(parameter.patrolPoints[patrolPosition]);
manager.transform.position = Vector2.MoveTowards(manager.transform.position,
parameter.patrolPoints[patrolPosition].position, parameter.moveSpeed * Time.deltaTime);
if (Vector2.Distance(manager.transform.position, parameter.patrolPoints[patrolPosition].position) < .1f)
manager.TransitionState(StateType.Patrol);
}
public void OnExit()
{
patrolPosition++;
if (patrolPosition>=parameter.patrolPoints.Length)
{
patrolPosition = 0;
}
}
}
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public enum StateType
{
Idel,Patrol,Chase,React,Attack
}
[Serializable]
public class Parameter
{
public int health;
public float moveSpeed;
public float chaseSpeed;
public float idleTime;
public Transform[] patrolPoints;
public Transform[] chasePoints;
public Animator animator;
}
public class FSM : MonoBehaviour
{
private IState currentState;
private Dictionary<StateType, IState> states = new Dictionary<StateType, IState>();
public Parameter parameter;
void Start()
{
states.Add(StateType.Idel, new IdleState(this));
states.Add(StateType.Patrol, new PatrolState(this));
parameter.animator = GetComponent<Animator>();
TransitionState(StateType.Idel);
}
void Update()
{
currentState.OnUpdate();
}
//设置当前状态
public void TransitionState(StateType type)
{
if (currentState != null)
currentState.onExit();
currentState = states[type];
currentState.OnEnter();
}
//修改朝向
public void FlipTo(Transform target)
{
if (target != null)
{
if (transform.position.x > target.position.x)
{
transform.localScale = new Vector3(1,1,-1);
}
else
{
transform.localScale = new Vector3(1, 1, 1);
}
}
}
}