TExcelTAD
Home › Game AI › Hierarchical State Machines

Hierarchical State Machines

Give a flat FSM a few more states (Patrol, Idle, Chase, Attack, Reload, Stunned, Dead) and the same transitions start appearing everywhere. "When hit by a stun grenade → Stunned" must be added to every state. "When the player is lost → go back to calm behaviour" must be added to Chase, Attack and Reload. A hierarchical state machine (HFSM) removes that duplication by nesting states inside super-states:

text
Root
├── Alive
│   ├── Calm            (initial)
│   │   ├── Patrol      (initial)
│   │   └── Idle
│   └── Combat
│       ├── Chase       (initial)
│       └── Attack
├── Stunned
└── Dead

A transition defined on a super-state applies to all of its children. Alive → Dead when health ≤ 0 is written once and works whether the agent is patrolling or attacking. Combat → Calm when the player is lost for 5 s covers Chase and Attack at once.

The rules of an HFSM

  1. The agent is in one leaf state, plus all of its ancestors. Being in Attack means being in Combat and in Alive.
  2. Every tick, check transitions from the outermost active state inwards. A transition on Alive beats one on Attack, so "die" always wins over "keep attacking".
  3. Entering a super-state enters its initial child (Combat → Chase).
  4. On a transition, exit states from the leaf up to the common ancestor, then enter from there down to the new leaf. Each level gets its Exit/Enter call, so Combat can draw its weapon once on enter and holster it once on exit, however many times the agent switches between Chase and Attack inside it.

An HFSM in C#

csharp · try it yourself
using System;
using System.Collections.Generic;

var root    = new State("Root");
var alive   = new State("Alive", root);
var calm    = new State("Calm", alive);
var patrol  = new State("Patrol", calm);
var idle    = new State("Idle", calm);
var combat  = new State("Combat", alive);
var chase   = new State("Chase", combat);
var attack  = new State("Attack", combat);
var stunned = new State("Stunned", root);
var dead    = new State("Dead", root);
root.Initial = alive; alive.Initial = calm; calm.Initial = patrol; combat.Initial = chase;

// Transitions live on the state where they apply; children inherit them.
alive.On(dead,     w => w.Health <= 0);
alive.On(stunned,  w => w.Stunned);
calm.On(combat,    w => w.SeesPlayer);
combat.On(calm,    w => !w.SeesPlayer);
chase.On(attack,   w => w.Dist <= 2);
attack.On(chase,   w => w.Dist > 2.5);
stunned.On(alive,  w => !w.Stunned);

var machine = new Hfsm(root);
var steps = new (string note, World w)[]
{
    ("quiet",         new World { Dist = 10 }),
    ("spots player",  new World { SeesPlayer = true, Dist = 6 }),
    ("closes in",     new World { SeesPlayer = true, Dist = 1.8 }),
    ("stun grenade",  new World { SeesPlayer = true, Dist = 1.8, Stunned = true }),
    ("recovers",      new World { SeesPlayer = true, Dist = 1.8 }),
    ("player hides",  new World { Dist = 8 }),
    ("shot dead",     new World { Dist = 8, Health = 0 }),
};
foreach (var (note, w) in steps)
{
    Console.WriteLine(
quot;-- {note}"); machine.Tick(w); Console.WriteLine(
quot; active: {machine.Path()}"); } class World { public bool SeesPlayer, Stunned; public double Dist; public int Health = 100; } class State { public readonly string Name; public readonly State? Parent; public State? Initial; public readonly List<(State to, Func<World, bool> when)> Transitions = new(); public State(string name, State? parent = null) { Name = name; Parent = parent; } public void On(State to, Func<World, bool> when) => Transitions.Add((to, when)); public int Depth => Parent == null ? 0 : Parent.Depth + 1; } class Hfsm { State leaf; public Hfsm(State root) { leaf = root; EnterDown(root); } List<State> Chain(State s) { var c = new List<State>(); for (var x = s; x != null; x = x.Parent) c.Insert(0, x); return c; } public string Path() => string.Join(" > ", Chain(leaf).ConvertAll(s => s.Name).GetRange(1, Chain(leaf).Count - 1)); void EnterDown(State s) { if (s.Parent != null) Console.WriteLine(
quot; enter {s.Name}"); leaf = s; if (s.Initial != null) EnterDown(s.Initial); } public void Tick(World w) { foreach (var s in Chain(leaf)) // outermost first foreach (var (to, when) in s.Transitions) if (when(w)) { Go(to); return; } } void Go(State target) { var from = Chain(leaf); var to = Chain(target); int common = 0; while (common < from.Count && common < to.Count && from[common] == to[common]) common++; if (common == to.Count) common--; // target is an ancestor: re-enter it for (int i = from.Count - 1; i >= common; i--) Console.WriteLine(
quot; exit {from[i].Name}"); for (int i = common; i < to.Count - 1; i++) Console.WriteLine(
quot; enter {to[i].Name}"); EnterDown(target); } }
   enter Alive
   enter Calm
   enter Patrol
-- quiet
   active: Alive > Calm > Patrol
-- spots player
   exit  Patrol
   exit  Calm
   enter Combat
   enter Chase
   active: Alive > Combat > Chase
-- closes in
   exit  Chase
   enter Attack
   active: Alive > Combat > Attack
-- stun grenade
   exit  Attack
   exit  Combat
   exit  Alive
   enter Stunned
   active: Stunned
-- recovers
   exit  Stunned
   enter Alive
   enter Calm
   enter Patrol
   active: Alive > Calm > Patrol
-- player hides
   active: Alive > Calm > Patrol
-- shot dead
   exit  Patrol
   exit  Calm
   exit  Alive
   enter Dead
   active: Dead

Read the exit/enter lines carefully. Switching from Chase to Attack exits and enters only the leaves: Combat stays active, so its "weapon drawn" setup isn't repeated. The stun grenade fires a transition defined on Alive, even though the active leaf was Attack, because outer transitions are checked first. When the stun wears off, the agent re-enters Alive through its initial children and starts again from Calm → Patrol, even though the player is still standing right there. It would only notice them on its next tick (here the player hides first). Finally, "shot dead" leaves the whole Alive branch through one rule written once.

History states

Restarting from Patrol after a stun is sometimes wrong: the agent was mid-fight and should resume it. A history state remembers the last active child of a super-state, and entering the super-state resumes that child instead of the initial one. In the model above you would store lastChild in each State when exiting it and use it in EnterDown instead of Initial. UML statecharts call this shallow history (remember one level) and deep history (remember the whole leaf path).

Tip: Use history sparingly in AI. Resuming a stale state ("Attack" against a target who has moved away) can look worse than restarting and re-evaluating. A common compromise: resume only if the stun lasted under a second or two.

HFSMs in the wild

Where What it looks like
Unity Animator sub-state machines group animation states; transitions can leave from "Any State"
Unreal StateTree states nest into a tree; a parent's tasks keep running while a child is active, and transitions can target any state
Godot AnimationTree AnimationNodeStateMachine nodes can contain nested state machines
Behavior trees a different structure, but they solve the same duplication problem with priorities; see Behavior Trees

The Unreal: EQS, StateTree & Perception lesson shows a real hierarchical state machine in an engine.

Test yourself

In the HFSM above, why does a stun interrupt the Attack state even though Attack has no stun transition?

  1. Because Attack is the initial state
  2. Because the transition is defined on the super-state Alive, which Attack is inside, and outer transitions are checked first
  3. Because stuns are random
  4. Because transitions are checked alphabetically

What happens to Combat's Enter/Exit when the agent switches between Chase and Attack?

  1. Combat exits and re-enters each time
  2. Nothing: Combat stays active, only the leaves exit and enter
  3. Combat is deleted
  4. Alive exits

What does a history state do?

  1. Logs every transition to a file
  2. Resumes the last active child when the super-state is re-entered
  3. Undoes the last transition
  4. Records the player's history