TExcelTAD
Home › Game AI › Finite State Machines

Finite State Machines

The finite state machine (FSM) is the workhorse of game AI. Most shipped enemies, from platformer goombas to the soldiers in big action games, are state machines underneath, or start as one. An FSM says: the agent is in exactly one state (Patrol, Chase, Attack, Search), each state has its own behaviour, and transitions with conditions move it between states.

text
              sees player                in range
   ┌────────┐ ───────────► ┌───────┐ ─────────────► ┌────────┐
   │ Patrol │              │ Chase │                │ Attack │
   └────────┘ ◄─────┐      └───────┘ ◄───────────── └────────┘
        ▲           │        │          out of range
        │  gave up  │        │ lost sight
        │           │        ▼
        │        ┌────────┐
        └─────── │ Search │
                 └────────┘

The State Machines lesson of the fundamentals course showed transition tables and the State pattern (Enter, Update, Exit). This lesson adds what AI state machines need on top: conditions instead of events, time in state, priorities, and hysteresis.

Transitions as data

For AI, transitions are usually conditions checked every think tick ("distance < 2"), not discrete events. Store them as a list of (from, to, condition) rules. The first rule whose condition is true wins, so the order of the list is the priority. A rule with from = null applies in every state ("any state" transitions, such as "health is 0 → Dead").

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

var rules = new List<Rule>
{
    new(null,     "Dead",   c => c.Health <= 0),                       // any state, highest priority
    new("Patrol", "Chase",  c => c.Sees && c.Dist < 8),
    new("Chase",  "Attack", c => c.Sees && c.Dist <= 2),
    new("Attack", "Chase",  c => c.Dist > 2.5),
    new("Chase",  "Search", c => !c.Sees),
    new("Search", "Chase",  c => c.Sees),
    new("Search", "Patrol", c => c.TimeInState >= 3),                  // give up after 3 s
};

var fsm = new Fsm("Patrol", rules);
//                    sees   dist  health
var timeline = new (bool, double, int)[]
{
    (false, 12, 100), (true, 7, 100), (true, 4, 100), (true, 2, 100), (true, 2, 80),
    (true, 3, 80), (false, 9, 80), (false, 9, 80), (false, 9, 80), (false, 9, 80),
    (true, 6, 80), (true, 1.5, 0),
};

foreach (var (sees, dist, health) in timeline)
    fsm.Tick(new Ctx { Sees = sees, Dist = dist, Health = health }, dt: 1.0);

record Rule(string? From, string To, Func<Ctx, bool> When);

class Ctx { public bool Sees; public double Dist; public int Health; public double TimeInState; }

class Fsm
{
    string state; double timeInState; int tick;
    readonly List<Rule> rules;
    public Fsm(string start, List<Rule> rules) { state = start; this.rules = rules; }

    public void Tick(Ctx c, double dt)
    {
        timeInState += dt;
        c.TimeInState = timeInState;
        string before = state;
        foreach (var r in rules)
        {
            if ((r.From == null || r.From == state) && r.To != state && r.When(c))
            {
                state = r.To;
                timeInState = 0;
                break;                                   // at most one transition per tick
            }
        }
        string change = before == state ? "" : 
quot; ({before} -> {state})"; Console.WriteLine(
quot;t={tick++,2} sees={(c.Sees ? 1 : 0)} dist={c.Dist,4:F1} hp={c.Health,3}: {state}{change}"); } }
t= 0 sees=0 dist=12.0 hp=100: Patrol
t= 1 sees=1 dist= 7.0 hp=100: Chase   (Patrol -> Chase)
t= 2 sees=1 dist= 4.0 hp=100: Chase
t= 3 sees=1 dist= 2.0 hp=100: Attack   (Chase -> Attack)
t= 4 sees=1 dist= 2.0 hp= 80: Attack
t= 5 sees=1 dist= 3.0 hp= 80: Chase   (Attack -> Chase)
t= 6 sees=0 dist= 9.0 hp= 80: Search   (Chase -> Search)
t= 7 sees=0 dist= 9.0 hp= 80: Search
t= 8 sees=0 dist= 9.0 hp= 80: Search
t= 9 sees=0 dist= 9.0 hp= 80: Patrol   (Search -> Patrol)
t=10 sees=1 dist= 6.0 hp= 80: Chase   (Patrol -> Chase)
t=11 sees=1 dist= 1.5 hp=  0: Dead   (Chase -> Dead)

Follow the log: Search starts at t=6, its timer reaches 3 s at t=9 and the guard gives up. At t=11 the player is in attack range, but the Dead rule is first in the list, so it wins over everything else. The whole behaviour is readable in seven lines of rules. A designer can reorder them, change the numbers, or load them from a file.

Note: Allowing only one transition per tick keeps the machine easy to follow. Some engines chain transitions in a single tick until no rule fires; that reacts faster, but a bad pair of rules can then loop forever in one frame. If you chain, cap the number of hops.

Hysteresis: stop the flicker

A classic FSM bug: the enemy attacks when the player is within 2 units and chases when they are further. A player standing at exactly 2.0 units, wobbling by a few centimetres, makes the enemy switch states every tick, restarting its attack animation each time. The fix is hysteresis: use a different threshold for leaving a state than for entering it. Here the attack starts at 2.0 but only stops beyond 2.5:

csharp · try it yourself
using System;

double[] distances = { 2.3, 2.1, 1.95, 2.05, 1.98, 2.08, 2.2, 2.6, 2.4 };

foreach (bool useHysteresis in new[] { false, true })
{
    string state = "Chase";
    int switches = 0;
    string log = "";
    foreach (double d in distances)
    {
        string next = state;
        if (state == "Chase" && d <= 2.0) next = "Attack";
        double leave = useHysteresis ? 2.5 : 2.0;
        if (state == "Attack" && d > leave) next = "Chase";
        if (next != state) switches++;
        state = next;
        log += state == "Attack" ? "A" : "c";
    }
    Console.WriteLine(
quot;{(useHysteresis ? "enter 2.0 / leave 2.5" : "single threshold 2.0"),-22} {log} switches: {switches}"); }
single threshold 2.0   ccAcAcccc  switches: 4
enter 2.0 / leave 2.5  ccAAAAAcc  switches: 2

With a single threshold the enemy switches four times in nine ticks (each A would restart the attack animation). With hysteresis it attacks once and stops only when the player really leaves. Use the same trick for every threshold the player can sit on: sight range (notice at 15 m, lose at 18 m), health-based fleeing (flee below 25%, return above 40%), cover (leave only if the new spot is clearly better). A short minimum time in state (for example 0.5 s) is a second, complementary guard.

Timers and time in state

Many AI transitions are about time: search for 3 seconds then give up, wait 1 second at each patrol point, attack at most once per 1.2 seconds. Keep timeInState in the machine and reset it on every transition, as Fsm.Tick does above; then "give up after 3 s" is a one-line rule instead of a timer variable scattered through the code.

When an FSM stops scaling

FSMs are perfect up to about 5–10 states. Beyond that, the number of transitions grows quickly: every new state ("Stunned", "Flee", "TakeCover", "Reload") needs transitions to and from most of the others, and you end up copying the same "if health ≤ 0 → Dead" or "if stunned → Stunned" rule into many states. Two common ways out:

Problem Fix Lesson
The same transitions copied into many states group states into super-states Hierarchical State Machines
Long chains of conditions and fallbacks a tree of priorities and sequences Behavior Trees
Many competing desires (hungry, tired, scared) scores instead of rules Utility AI
Multi-step goals that change with the world a planner Goal-Oriented Action Planning

Tip: Don't abandon FSMs because they're "old". Unreal's StateTree and Unity's Behavior graphs are both largely structured state machines, and an animation state machine drives almost every character. A small, readable FSM is often the best AI in the game.

Test yourself

In a rule list where the first matching rule wins, what decides priority?

  1. The alphabetical order of states
  2. The order of the rules in the list
  3. The number of conditions
  4. The most recent state

What does hysteresis do in a state machine?

  1. Makes transitions random
  2. Uses different thresholds to enter and leave a state, so values near the boundary don't cause flicker
  3. Speeds up transitions
  4. Removes the need for states

Why reset timeInState on every transition?

  1. To save memory
  2. So rules like 'give up searching after 3 s' measure time since entering the current state
  3. Because C# requires it
  4. To make the AI faster