Article
Game AI - Finite State Machines and Hierarchical State Machines
The most common tool in game AI. A guard patrols, investigates, chases, attacks and flees, and can also be stunned by a flashbang — written as a flat state machine that takes 33 transitions; as a hierarchical one, only 12. This article implements a general-purpose hierarchical state machine and verifies, with random input, that it behaves exactly like the flat version and a hand-written switch.
Game AI does not share the goals of academic artificial intelligence. It does not pursue the “optimal”; it pursues believable, controllable, tunable. A guard has to look smart, but not so smart that the player has no way out; a designer has to be able to see why the AI did what it did, and to change it. That is why the tools of game AI are mostly plain:
Section | Method | The question it answers |
|---|---|---|
3.1 – 3.2 | State machines, behaviour trees | What mode is the character in now, and when does it switch? |
3.3 – 3.4 | GOAP, utility AI | With several goals, which one to pick and how to reach it |
3.5 – 3.6 | Steering behaviours, influence maps | How to move, and how to read the situation on the map |
3.7 – 3.8 | Minimax, Monte Carlo tree search | In a turn-based match, what to play next |
3.9 | Vision and perception | What the character can see |
This article starts with the most basic and most frequently used of them: the finite state machine.
Finite state machines
A guard's behaviour can be divided into a handful of modes: patrol, investigate, chase, attack, flee. Within each mode what it does is simple; what is complicated is switching between them:
patrolling and sees the player → chase;
chasing and close enough → attack; too far → keep chasing;
hasn't seen the player for two seconds → go and investigate the last place it saw them;
health below 30 → flee; back above 60 → patrol again.
That is the finite state machine (FSM): a finite set of states, exactly one of which it occupies at any moment; between the states there are transitions, each with a condition, and when the condition holds it switches to the target state.
The most common way to write one is an enum plus a switch:
// Hand-written switch: the most common way to do it. An enum holds the state, and resume remembers
// what the guard was doing before it was stunned
enum class Guard { Patrol, Investigate, Chase, Attack, Flee, Stunned, Dead };
inline const char* guardName(Guard g) {
const char* names[] = {"Patrol", "Investigate", "Chase", "Attack", "Flee", "Stunned", "Dead"};
return names[static_cast<int>(g)];
}
struct GuardSwitch {
Guard state = Guard::Patrol;
Guard resume = Guard::Patrol;
void enter(Guard s, GuardCtx& c) {
state = s;
if (s == Guard::Investigate) guard::startInvestigating(c);
if (s == Guard::Stunned) guard::startStun(c);
}
void update(GuardCtx& c) {
using namespace guard;
if (state == Guard::Dead) return;
if (dead(c)) return enter(Guard::Dead, c);
if (state != Guard::Stunned && stunned(c)) {
resume = state;
return enter(Guard::Stunned, c);
}
switch (state) {
case Guard::Patrol:
if (lowHealth(c)) enter(Guard::Flee, c);
else if (sees(c)) enter(Guard::Chase, c);
else if (noise(c)) enter(Guard::Investigate, c);
break;
case Guard::Investigate:
if (lowHealth(c)) enter(Guard::Flee, c);
else if (sees(c)) enter(Guard::Chase, c);
else if (investigateDone(c)) enter(Guard::Patrol, c);
break;
case Guard::Chase:
if (lowHealth(c)) enter(Guard::Flee, c);
else if (lostTrack(c)) enter(Guard::Investigate, c);
else if (inRange(c)) enter(Guard::Attack, c);
break;
case Guard::Attack:
if (lowHealth(c)) enter(Guard::Flee, c);
else if (lostTrack(c)) enter(Guard::Investigate, c);
else if (outOfRange(c)) enter(Guard::Chase, c);
break;
case Guard::Flee:
if (recovered(c)) enter(Guard::Patrol, c);
break;
case Guard::Stunned:
if (stunOver(c)) enter(resume, c);
break;
case Guard::Dead: break;
}
}
};All the transition conditions are defined in one place and shared by the three implementations below:
struct GuardCtx {
// Perception input (written by the game every frame)
float t = 0; // current time (seconds)
bool seesPlayer = false;
float playerDist = 10; // distance to the player (metres)
bool heardNoise = false;
bool stunEvent = false; // hit by a flashbang this frame
float health = 100;
float lastSeen = -1e9f; // the moment the player was last seen
// Timers the state machine keeps for itself
float investigateUntil = 0;
float stunUntil = 0;
};
// Every transition condition lives here, shared by the three implementations
namespace guard {
inline bool dead(const GuardCtx& c) { return c.health <= 0; }
inline bool stunned(const GuardCtx& c) { return c.stunEvent; }
inline bool lowHealth(const GuardCtx& c) { return c.health < 30; }
inline bool recovered(const GuardCtx& c) { return c.health > 60; }
inline bool sees(const GuardCtx& c) { return c.seesPlayer; }
inline bool noise(const GuardCtx& c) { return c.heardNoise; }
inline bool investigateDone(const GuardCtx& c) { return c.t > c.investigateUntil; }
inline bool lostTrack(const GuardCtx& c) { return c.t - c.lastSeen > 2; }
inline bool inRange(const GuardCtx& c) { return c.playerDist < 1.5f; }
inline bool outOfRange(const GuardCtx& c) { return c.playerDist > 2; }
inline bool stunOver(const GuardCtx& c) { return c.t > c.stunUntil; }
inline void startInvestigating(GuardCtx& c) { c.investigateUntil = c.t + 3; }
inline void startStun(GuardCtx& c) { c.stunUntil = c.t + 1.5f; }
} // namespace guardThis is direct and fast, and entirely sufficient when there are only a few states. The trouble starts when the number of states grows.
State explosion
Give the guard two events that can “happen at any time”:
Death: health reaches zero, and the guard dies immediately whatever it was doing;
Stunned: hit by a flashbang, stunned for 1.5 seconds, and then it goes back to what it was doing.
Look at the top of the switch version: death and being stunned are hoisted out of the switch, because every state needs them. “Flee when health is low” is also written out again in each of the four branches — patrol, investigate, chase, attack. Worse is “go back to what it was doing”: a state machine only remembers the current state, so once it is stunned it has forgotten what it was up to, and an extra resume variable has to remember it.
What happens if you insist on a pure state machine — nothing but states and transitions, no extra variables?
// The same behaviour written as a flat state machine: every state has to check "death", "stunned" and
// "low health" for itself, and to get "back to the previous state after a stun" every origin needs
// a Stunned state of its own
inline int buildGuardFlat(HfsmDef<GuardCtx>& m) {
using namespace guard;
int patrol = m.addState("Patrol");
int investigate = m.addState("Investigate", -1, startInvestigating);
int chase = m.addState("Chase");
int attack = m.addState("Attack");
int flee = m.addState("Flee");
int dead = m.addState("Dead");
int normal[] = {patrol, investigate, chase, attack, flee};
int stunnedFrom[5];
for (int i = 0; i < 5; ++i) stunnedFrom[i] = m.addState("Stunned", -1, startStun);
for (int i = 0; i < 5; ++i) {
m.addTransition(normal[i], dead, guard::dead);
m.addTransition(normal[i], stunnedFrom[i], stunned);
}
for (int x : {patrol, investigate}) {
m.addTransition(x, flee, lowHealth);
m.addTransition(x, chase, sees);
}
m.addTransition(patrol, investigate, noise);
m.addTransition(investigate, patrol, investigateDone);
for (int x : {chase, attack}) {
m.addTransition(x, flee, lowHealth);
m.addTransition(x, investigate, lostTrack);
}
m.addTransition(chase, attack, inRange);
m.addTransition(attack, chase, outOfRange);
m.addTransition(flee, patrol, recovered);
for (int i = 0; i < 5; ++i) {
m.addTransition(stunnedFrom[i], dead, guard::dead);
m.addTransition(stunnedFrom[i], normal[i], stunOver);
}
return patrol; // initial state
}Every state has to repeat “death”, “stunned” and “low health” for itself. And to get “back to the previous state after a stun”, every origin needs its own copy of Stunned: stunned while patrolling, stunned while chasing... five of them in all. The result is 11 states and 33 transitions. Each global event you add multiplies the transition count by the number of states.
Hierarchical state machines
Look at those duplicated transitions: they really belong to a group of states rather than to any single state. “Flee when health is low” holds for both patrol and investigate, because both belong to “calm”; “death” holds for every living state.
A hierarchical state machine (HFSM) allows states to be nested. A transition on a parent state applies to all of its child states. The guard's behaviour can then be organised as:
Alive├─ Active
│ ├─ Calm ── Patrol, Investigate
│ ├─ Combat ── Chase, Attack
│ └─ Flee
└─ Stunned
Dead
“Death” hangs on Alive, and one transition is enough; “stunned” hangs on Active; “low health” hangs on Calm and Combat. Going from Stunned back to Active uses a history transition: it restores the child state that Active was in when it was left, with no extra variables at all.
struct GuardStates {
int alive, active, calm, patrol, investigate, combat, chase, attack, flee, stunned, dead;
};
inline GuardStates buildGuardHfsm(HfsmDef<GuardCtx>& m) {
using namespace guard;
GuardStates s;
s.alive = m.addState("Alive");
s.active = m.addState("Active", s.alive);
s.calm = m.addState("Calm", s.active);
s.patrol = m.addState("Patrol", s.calm);
s.investigate = m.addState("Investigate", s.calm, startInvestigating);
s.combat = m.addState("Combat", s.active);
s.chase = m.addState("Chase", s.combat);
s.attack = m.addState("Attack", s.combat);
s.flee = m.addState("Flee", s.active);
s.stunned = m.addState("Stunned", s.alive, startStun);
s.dead = m.addState("Dead");
m.addTransition(s.alive, s.dead, dead); // applies to every living state
m.addTransition(s.active, s.stunned, stunned); // applies to Calm, Combat, Flee and their children
m.addTransition(s.calm, s.flee, lowHealth);
m.addTransition(s.calm, s.combat, sees);
m.addTransition(s.patrol, s.investigate, noise);
m.addTransition(s.investigate, s.patrol, investigateDone);
m.addTransition(s.combat, s.flee, lowHealth);
m.addTransition(s.combat, s.investigate, lostTrack);
m.addTransition(s.chase, s.attack, inRange);
m.addTransition(s.attack, s.chase, outOfRange);
m.addTransition(s.flee, s.calm, recovered);
m.addTransition(s.stunned, s.active, stunOver, /*resume=*/true); // history transition: back to the state it was stunned in
return s;
}11 states, 7 of them leaves, and 12 transitions — and every transition is written where it actually belongs.
Implementation
The state machine splits into two parts: the definition (which states exist, which transitions exist, what happens on entry and exit) and the instance (which state a particular character is currently in). All guards share a single definition; each guard only has to remember its own current state. The measurements below show why this matters.
template <class Ctx>
class HfsmDef {
public:
using Action = std::function<void(Ctx&)>;
using Condition = std::function<bool(const Ctx&)>;
struct State {
std::string name;
int parent = -1;
int depth = 0;
int initial = -1; // the initial child state of a composite state; -1 means a leaf
Action onEnter, onUpdate, onExit;
std::vector<int> transitions; // this state's own transitions, in the order they were added
};
struct Transition {
int from, to;
Condition when;
bool resume; // true: a history transition, restoring the last child state when entering a composite state
};
int addState(std::string name, int parent = -1, Action onEnter = {}, Action onUpdate = {}, Action onExit = {}) {
int depth = parent < 0 ? 0 : states_[parent].depth + 1;
states_.push_back({std::move(name), parent, depth, -1, std::move(onEnter), std::move(onUpdate), std::move(onExit), {}});
int id = static_cast<int>(states_.size()) - 1;
if (parent >= 0 && states_[parent].initial < 0) states_[parent].initial = id; // the first child state is the initial one by default
return id;
}
void setInitial(int parent, int child) { states_[parent].initial = child; }
// from may be a composite state: the transition is checked as long as any of its descendants is active
void addTransition(int from, int to, Condition when, bool resume = false) {
transitions_.push_back({from, to, std::move(when), resume});
states_[from].transitions.push_back(static_cast<int>(transitions_.size()) - 1);
}
const std::vector<State>& states() const { return states_; }
const std::vector<Transition>& transitions() const { return transitions_; }
private:
std::vector<State> states_;
std::vector<Transition> transitions_;
};On each update, the transitions of every level are checked in turn, from the outermost ancestor down to the current leaf. Outer levels take priority: if “death” and “sees the player” both hold, the “death” transition hanging on Alive is checked first. This is one of the most useful properties of a hierarchical state machine: an emergency can always interrupt routine behaviour.
// Every update: check the transitions of each level in turn, from the outermost ancestor down to the
// current leaf, and take the first one that holds immediately (outer priority); then run onUpdate over
// the active states, from the outside in. At most one transition happens per update
void update(Ctx& ctx) {
const auto& states = def_->states();
int chain[kMaxDepth];
int n = fillChain(chain); // root → leaf
for (int k = 0; k < n; ++k)
for (int ti : states[chain[k]].transitions) {
const auto& t = def_->transitions()[ti];
if (t.when(ctx)) {
changeTo(t.to, t.resume, ctx);
++transitionsTaken_;
n = fillChain(chain);
goto updated;
}
}
updated:
for (int k = 0; k < n; ++k)
if (states[chain[k]].onUpdate) states[chain[k]].onUpdate(ctx);
}Changing state has to call the exit and entry actions correctly. Exit upwards from the current leaf until the least common ancestor of it and the target; then enter downwards from that common ancestor until the target; and if the target is a composite state, keep going down along its initial child state (or its recorded history) until a leaf is reached. Take being stunned while in Attack:
exit
Attack,Combat,Active(the least common ancestor isAlive, which does not exit);enter
Stunned.
1.5 seconds later the history transition returns to Active: enter Active, which remembers it was last in Combat; enter Combat, which remembers it was last in Attack; enter Attack.
void changeTo(int target, bool resume, Ctx& ctx) {
const auto& states = def_->states();
// Least common ancestor. When the target is the current leaf itself or one of its ancestors, treat
// it as an "external transition": exit the target first, then re-enter it
int a = leaf_, b = target;
while (states[a].depth > states[b].depth) a = states[a].parent;
while (states[b].depth > states[a].depth) b = states[b].parent;
while (a != b) a = states[a].parent, b = states[b].parent;
int lca = a;
if (lca == target) lca = states[target].parent;
// 1. exit upwards from the leaf until the least common ancestor (exclusive)
for (int s = leaf_; s != lca; s = states[s].parent) {
if (states[s].onExit) states[s].onExit(ctx);
if (int p = states[s].parent; p >= 0) lastChild_[p] = s; // remember the child state we left
}
// 2. enter downwards from the least common ancestor towards the target
enterDown(target, lca, resume, ctx);
}
// Enter target: first enter every ancestor between from (exclusive) and target, then enter target,
// then follow the initial child states (or the history) all the way down to a leaf
void enterDown(int target, int from, bool resume, Ctx& ctx) {
const auto& states = def_->states();
int path[kMaxDepth], n = 0;
for (int s = target; s != from; s = states[s].parent) path[n++] = s;
for (int k = n - 1; k >= 0; --k)
if (states[path[k]].onEnter) states[path[k]].onEnter(ctx);
int s = target;
while (states[s].initial >= 0) {
int child = resume && lastChild_[s] >= 0 ? lastChild_[s] : states[s].initial;
if (states[child].onEnter) states[child].onEnter(ctx);
s = child;
}
leaf_ = s;
}A unit test uses a small hand-written state machine to verify the entry and exit order one case at a time: the least common ancestor does not exit, outer transitions take priority, when the target is one of its own ancestors it exits first and then re-enters, and multi-level history is restored one level at a time.
Are the three implementations really equivalent?
A hierarchical state machine, a flat state machine and a hand-written switch should all behave identically. The unit test drives three guards with random but persistent input — the player appears and disappears, the distance performs a random walk, noise is sometimes heard, the guard is sometimes stunned, sometimes taking damage and sometimes healing — 300 runs each, 1500 frames per run:
across 450,000 frames all three were in exactly the same state, not one frame differed;
every state was visited; recovery after a stun into patrol, investigate, chase, attack and flee happened 83, 436, 1856, 411 and 137 times respectively, so every case of the history transition was covered.
The test is also good at catching mistakes: switching “outer priority” to “inner priority”, removing the history record, not finding the least common ancestor on exit, or making one of the flat version's Stunned states return to the wrong place — each of them fails immediately.
The mouse is the player. The guard patrols along the dashed line, the wedge is its field of view, and the pillars block line of sight; at very close range it notices you even outside the cone. Click the field to throw a stone and make a noise. flash is the flashbang, shoot takes 25 health off the guard, revive brings it back. The highlight on the right is the chain of active states, and below it the most recent transitions.
A few small experiments worth trying:
Move the mouse into the guard's field of view: it switches to
Combat, comes after you, and starts attacking once it is close. Watch the right-hand side:Alive,Active,CombatandAttackall light up together.Hide behind a pillar: after two seconds the guard switches to
Investigate, walks to the place it last saw you, looks around for a while, and then goes back to patrolling.Press flash while the guard is attacking: it is stunned, and 1.5 seconds later it returns straight to
Attackinstead of starting over from patrol. Press flash while it is patrolling and it carries on patrolling when it recovers. That is the history transition.Press shoot three times in a row: health drops below 30 and the guard flees. Whether it was patrolling or fighting at the time, the transition hanging on
CalmandCombattakes effect.Throw a stone while the guard is fleeing: it ignores it. The flee state has no “heard a noise” transition, which is exactly what we want.
Measured: the cost of a general-purpose state machine
Ten thousand guards, each running 100 frames, measuring the time per guard per frame (input generated in advance, only the state machine itself counted):
Implementation | Per guard, per frame |
|---|---|
Hand-written | 4.5 ns |
Flat state machine, first version | 224 ns |
Hierarchical state machine, first version | 340 ns |
Flat state machine, without the per-frame allocation | 95–118 ns |
Hierarchical state machine, without the per-frame allocation | 174–193 ns |
Flat state machine, all guards sharing one definition | 19 ns |
Hierarchical state machine, all guards sharing one definition | 25 ns |
The first version was 50–75 times slower, for two reasons, neither of which has anything to do with the idea of a state machine — both are implementation problems:
Allocating memory every frame. The first version's
updateput the chain of active states into a freshstd::vectorevery time, twice per frame. Switching to fixed-size arrays made it twice as fast.One complete definition per guard. Every guard stored the names of all the states and the condition function of every transition, so the data for ten thousand guards was scattered all over memory and almost every access was a cache miss. The verification is simple: with only 100 guards, whose data all fits in cache, the same code was just 4–6 times slower than
switch. Once the definition was split out and shared by all guards, each guard kept only a current state and a short history, and the cost dropped to 19–25 nanoseconds.
The final version is still 4–6 times slower than a hand-written switch: every condition is a std::function call, which the compiler cannot inline. But 25 nanoseconds means ten thousand guards cost only 0.25 milliseconds per frame. In a real game, perception — line-of-sight tests, pathfinding queries — costs orders of magnitude more, and the overhead of the state machine itself is negligible.
Test environment
Apple M3, Apple clang 21,
-O2, best of 5 runs. The machine was extremely busy during the measurement (load average went above 170 at one point), so the table gives the range across several runs; the conclusions were consistent. The code is incpp/ai/fsm/fsm_bench.cpp.
The limits of state machines
A hierarchical state machine solves the duplicated-transition problem, but as behaviour grows more complex it still runs into bottlenecks:
The transitions form a mesh. Every state has to know where it can go, and adding one new state often means editing the transitions of several old ones.
Hard to reuse. Snippets like “walk somewhere and do something” are written over and over again in different states.
Hard to express “do several things in order”: walk to the door, open it, go in, close it. Written as a state machine, every step is a state, and once you add the handling for failure it quickly becomes a mess.
The next article, on behaviour trees, exists precisely to solve these problems: it organises behaviour into a tree, expresses logic with composite nodes such as “sequence” and “selector”, and nodes no longer need to know about each other.
Common pitfalls
Problem | Cause | Fix |
|---|---|---|
The state flickers back and forth between two states | Two transitions have opposite conditions and alternate around the threshold | Add hysteresis: enter attack at 1.5 m, leave it at 2 m (as this article does) |
Emergencies are ignored | Transitions of inner states are checked first | Outer priority; hang global events on the outermost state |
After an interruption it starts over from the beginning | The state machine does not remember what it was doing | History transitions |
Exit actions never run, timers and animations are left behind | A cross-level switch only exits the leaf | Exit all the way up to the least common ancestor, running the exit actions level by level |
Several transitions in one frame make behaviour unpredictable | Transitions are re-checked immediately after a switch | At most one transition per update (as this article does), or cap the number |
The state machine gets slow once there are many characters | Every character holds its own complete copy of the definition | Separate definition from instance; keep a single definition |
Adding one global event means editing every state | It is a flat state machine | Go hierarchical: hang it on a parent state |
Applications in games
Character AI: starting with the ghosts in Pac-Man (chase, scatter and frightened modes), the state machine has been the most common structure in game AI. The enemies in many action games are still implemented as hierarchical state machines.
Animation state machines: Unity's Animator and Unreal's animation blueprints are both visual hierarchical state machines: idle, walk, run and jump are each a state, switched by parameter conditions, with support for sub-state machines.
Game flow: main menu, loading, in-game, paused, results — that is a state machine.
UI, network connections, level events: any logic of the form “be in some mode, switch when an event arrives” is well described by a state machine.
Further reading
David Harel, Statecharts: A Visual Formalism for Complex Systems (1987): the original paper on hierarchical states, history states and parallel regions
Mat Buckland, Programming Game AI by Example (2005), chapter 2: state machines in games, including global states and state stacks
Ian Millington and John Funge, Artificial Intelligence for Games (2nd edition, 2009), section 5.3: state machines and hierarchical state machines
Robert Nystrom, Game Programming Patterns: State: from
switchto the state pattern, then on to hierarchical state machines and pushdown automata
Newsletter
Subscribe
Get an email when a new article is published. Unsubscribe anytime.
Copyright
Copyright of this article belongs to its author or rights holder. When reposting or quoting, please follow the applicable license terms and keep the link to this article.
XuYi, “Game AI - Finite State Machines and Hierarchical State Machines”, https://xuyi.dev/en/2026-11-25-qecsmh
Comments
Comments
Loading comments…