----What is a finite state machine-----------------------------------
finite state machines have a limited number of States, and each state can switch to 0 or more states, and the input determines the migration of the next state.
finite state machines are divided into two types: deterministic non-deterministic, and non-deterministic finite state machines can be converted to deterministic finite state machines.
----Considerations for finite state machines-----------------------------
For example, after being attacked, turn to the enemy, release the skill and switch to the resting state if the enemy is too strongwill run away, these problems are first intuitive to use if else statements, which can be very difficult to write, and the changes will be cumbersome, this time using a "finite state machine" to solve.
----Module Design-------------------------------------------
State :is the base class of a finite state machine, which is an abstract class that contains some common members and methods. As a base class, can be inherited by the quilt class, so the method is virtual, so that the implementation of polymorphism. When used, you caninherited from the state, you can override the base class Onenter/ontick/onexit and other methods to achieve some personalized operation.
public abstract class State{ protected State (Character Character) {Character = Character; }Public Character Character { get; Private set; }Public virtual void OnEnter () { }Public virtual State OnTick () { return this; }Public virtual void OnExit () { }}public class Idle : State{Public Idle (Character Character): base(character) { }Public override State OnTick () {Character.play (character.idle); return this; }}
----Concrete Implementation-------------------------------------------
public abstract class Character : monobehaviour { Private State State; //Indicates the current state Public State State { Get { return state; } protected set { If (state = = null)state = new Idle(this); if (state! = value) { var old_state = State;state = value; //Notification status Toggle onstatechanged (state, old_state); //Call the Exit method of the previous state old_state. OnExit (); //Enter current current state State . OnEnter (); } } } protected virtual void onstatechanged ( State new_state, State old_ State) { } void Update() { If (state = null) //Ontick method that invokes the current state at each frame, toggles the state based on its return value state = State.ontick (); }}
From for notes (Wiz)
Ai's finite state machine