How to create Finite State Machine for a game agent
Notes:
Finite state machines:
Finite state machine is an abstract model containing finite set of states, an initial state, set of inputs and a transition function that maps current state, input and Nextstate.
Finite state machine can be in only one of the finite number of states at any given time.
FSM can be represented graphically, where the nodes represent states, edges represent transitions and label on the edge represents the transition condition (i.e. an input).
Nodes are represented by circle shapes, edges are represented by directed lines.
Example 1: State diagram for simple Light bulb Model
off - button pressed - on
on - button released - off
Example 2: Sate diagram for a simple Enemy Model
wander - player is within sight – attack
attack - player is out of sight - wander
attack - player is attacking - evade
evade - player is idle - attack
Example Code: Enemy Model
class Enemy
{
enum States{wander,attack,evade}
States state = States.wander;
void Update() // update loop // infinite loop
{
switch(state)
{
case States.wander:
// play enemy wander animation
if(player is within the sight)
state = States.attack;
break;
case States.atttack:
// play enemy attack animation
if(player is out of sight)
state = States.wander;
if(player is attacking)
state = States.Evade;
break;
case States.evade:
// play enemy evade animation
if(player is idle)
state = States.attack;
break;
}
}
}
Game designers design FSMs for game agents in such a manner that, game agents behave intelligently. FSMs help game programmers to program easily and efficiently. FSM are used to implement game agents logic.
Note: If there are one or two states to manage we can use if then, as number of states increase we take help of switch case (i.e. FSM), design patter, etc.