One time when I was working on one of my first 2D platformer I had to implement an enemy - shooting alien. At beginning his behaviour was very simple - when player enters in his vision range he starts shooting. So in I use bunch of if statements in Update() method. Later when AI behaviour became more complex I understood that I need to discover better way to solve this problem. And I found a solution - finite-state machines.
What is finite-state machine?
Finite-state machine (FSM) is a mathematical model of computation. Every FSM meets requirements:
- FSM has a fixed set of states that it can be in, for example: walking, jumping, running, idle,
- it can only be in one state at time - character can't simultaneously walking and jumping,
- inputs or events are sent to the machine - when player press keyboard button for example,
- each state has a set of transitions which describes conditions allow to switch to another state. For example pressing Spacebar switch character from idle state to jump state.
Basic finite-state machine
There is no hierarchy in basic finite-state machine. It means that the choice of whether to continue or move into another state is evaluated completely inside the state that AI is currently in.
Finite-state machine in computer games
The behaviour of state machines can be observed in many modern devices that perform a sequence of actions depending on sequence of events with which they are presented. Examples are vending machines, elevators, traffic lights and combinations locks. Game developers noticed that finite-state machines can be used to AI programming. FSM allows to get great results without complex code. They are relatively easy to understand, implement and debug.
To implement FSM for enemy AI we should enter to his brain and recognize all actions that enemy can perform. For example, the ghost in Pac Man can chase the player, evade him or roam freely. Ghosts in each of this states behave diferrently and their transitions are determined by the player's actions - when player eats a pill, state will change from chasing to evading.
Finite-state machine example
Ok, I will show you an example of implementation finite-state machine which control an enemy in shooter game. First let's create IState interface: