Game Development Reference
In-Depth Information
Decision making - Finite State Machine
Decision making for AI can be handled in many different ways, and one common way is to
use a
Finite State Machine
(
FSM
). An FSM contains a number of predefined states. Each
state has a set of functionality and behavior tied to it. Each state also has a number of con-
ditions for when it can change to another state.
In this recipe, we'll define a state machine that will emulate a common AI behavior in
games. In fact, it will be more advanced than many games, which usually have AI that can
only either move around on a path, or attack. Our AI will have three states,
Patrol
,
Attack
,
and
Retreat
, as shown in the following diagram:.
State diagram
The
PatrolState
will be the default and fallback state. It will perform random move-
ment and will switch to
AttackState
if it spots an enemy.
The
AttackState
will handle firing and ammunition and will attack a target as long as
it's visible and it has ammunition left. Then it will either return to
PatrolState
or flee
using
RetreatState
.