TExcelTAD
Home › Game AI › Behavior Trees

Behavior Trees

A behavior tree (BT) organizes an agent's behaviour as a tree of small nodes that are re-evaluated from the root many times per second. Behavior trees became the standard for game AI after Halo 2 (2004) because they scale better than state machines: instead of wiring transitions between every pair of states, you list behaviours in priority order, and the tree picks the first one that can run.

Status: the one idea behind everything

Every node, when ticked, returns one of three values:

Status Meaning
Success I did it (or the condition is true).
Failure I can't do it (or the condition is false).
Running I'm still working on it; tick me again next time.

Running is what makes BTs work in games: "move to the door" takes many frames, so the move node returns Running until the agent arrives.

The core nodes

Node Kind Behaviour
Sequence (→) composite ticks children left to right; fails at the first failure, returns Running if a child is running, succeeds if all succeed. "Do A, then B, then C."
Selector (?) / Fallback composite ticks children left to right; succeeds at the first success, returns Running if a child is running, fails if all fail. "Try A, else B, else C."
Condition leaf checks something, returns Success or Failure, never Running
Action leaf does something, returns any of the three
Decorator one child changes the child's result or when it runs (invert, repeat, cooldown); see Decorators, Running & Aborts

A typical guard tree, highest priority on the left:

text
? Root (Selector)
├── → Attack (Sequence)
│   ├── Condition: can see player
│   ├── Condition: player within 2 m
│   └── Action: swing sword
├── → Chase (Sequence)
│   ├── Condition: can see player
│   └── Action: move to player
└── Action: patrol

Read it as a sentence: "If you can see the player and they are close, attack; otherwise, if you can see them, chase; otherwise, patrol." Adding "flee when health is low" means inserting one more branch on the left. No other branch changes.

A behavior tree engine in C#

The whole engine is about 40 lines. Each node prints its result with indentation, so the output is a trace of one tick through the tree.

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

var bb = new Agent();   // the agent's data that nodes read and write
Node tree = new Selector("Root",
    new Sequence("Attack",
        new Condition("can see player", () => bb.SeesPlayer),
        new Condition("player within 2", () => Math.Abs(bb.PlayerX - bb.X) <= 2),
        new Act("swing sword", () => { Console.WriteLine("        * swing! *"); return Status.Success; })),
    new Sequence("Chase",
        new Condition("can see player", () => bb.SeesPlayer),
        new Act("move to player", () =>
        {
            bb.X += Math.Clamp(bb.PlayerX - bb.X, -1.5, 1.5);
            return Math.Abs(bb.PlayerX - bb.X) <= 2 ? Status.Success : Status.Running;
        })),
    new Act("patrol", () => Status.Running));

var world = new (bool sees, double px)[] { (false, 9), (true, 6), (true, 6), (true, 6), (true, 6) };
for (int t = 0; t < world.Length; t++)
{
    (bb.SeesPlayer, bb.PlayerX) = world[t];
    Console.WriteLine(
quot;tick {t}: guard at {bb.X:F1}, player at {bb.PlayerX:F1}, sees={bb.SeesPlayer}"); tree.Tick(0); } class Agent { public double X, PlayerX; public bool SeesPlayer; } enum Status { Success, Failure, Running } abstract class Node { public readonly string Name; protected Node(string name) => Name = name; public Status Tick(int depth) { Status s = Run(depth); Console.WriteLine(
quot;{new string(' ', depth * 2)}{Name}: {s}"); return s; } protected abstract Status Run(int depth); } class Sequence : Node { readonly Node[] kids; public Sequence(string name, params Node[] kids) : base(name) => this.kids = kids; protected override Status Run(int depth) { foreach (var k in kids) { Status s = k.Tick(depth + 1); if (s != Status.Success) return s; // Failure or Running stops the sequence } return Status.Success; } } class Selector : Node { readonly Node[] kids; public Selector(string name, params Node[] kids) : base(name) => this.kids = kids; protected override Status Run(int depth) { foreach (var k in kids) { Status s = k.Tick(depth + 1); if (s != Status.Failure) return s; // Success or Running stops the selector } return Status.Failure; } } class Condition : Node { readonly Func<bool> test; public Condition(string name, Func<bool> test) : base(name) => this.test = test; protected override Status Run(int depth) => test() ? Status.Success : Status.Failure; } class Act : Node { readonly Func<Status> action; public Act(string name, Func<Status> action) : base(name) => this.action = action; protected override Status Run(int depth) => action(); }
tick 0: guard at 0.0, player at 9.0, sees=False
    can see player: Failure
  Attack: Failure
    can see player: Failure
  Chase: Failure
  patrol: Running
Root: Running
tick 1: guard at 0.0, player at 6.0, sees=True
    can see player: Success
    player within 2: Failure
  Attack: Failure
    can see player: Success
    move to player: Running
  Chase: Running
Root: Running
tick 2: guard at 1.5, player at 6.0, sees=True
    can see player: Success
    player within 2: Failure
  Attack: Failure
    can see player: Success
    move to player: Running
  Chase: Running
Root: Running
tick 3: guard at 3.0, player at 6.0, sees=True
    can see player: Success
    player within 2: Failure
  Attack: Failure
    can see player: Success
    move to player: Success
  Chase: Success
Root: Success
tick 4: guard at 4.5, player at 6.0, sees=True
    can see player: Success
    player within 2: Success
        * swing! *
    swing sword: Success
  Attack: Success
Root: Success

Children print before their parent because a parent only knows its own result once its children have returned. Read each tick bottom-up:

  • Tick 0: the guard can't see the player, so both sequences fail at their first condition and the selector falls through to patrol, which is Running.
  • Tick 1: the player is visible but 6 units away. Attack fails at "player within 2", Chase's move returns Running, and the selector stops there: patrol isn't even ticked.
  • Ticks 2–3: the guard closes in 1.5 units per tick. At tick 3 it arrives within 2 units after Attack was checked, so the move returns Success and so does Chase.
  • Tick 4: now Attack's conditions pass, the sword swings, and Chase isn't ticked at all.

Notice that the tree is evaluated from the root every tick. That's what makes BTs reactive: the moment the player becomes visible, the higher-priority branch takes over, with no transition to write.

Behavior trees vs state machines

FSM Behavior tree
Structure states + transitions (a graph) priorities + sequences (a tree)
Adding a behaviour add transitions to and from many states insert one branch
"What is it doing now?" the current state the path to the running leaf
Reacting to change a transition must exist re-evaluated from the root each tick
Best for few states with clear switches, animation many prioritized behaviours, designer-edited AI
Cost cheap more ticks per decision; mitigated by event-driven trees and aborts

Engines ship BT editors: Unreal's Behavior Tree with its Blackboard (see Unreal: AIController, Behavior Trees & Blackboard) and Unity's Behavior package graphs (see Unity: AI Navigation & Behavior). For your own C++ engine, BehaviorTree.CPP is a widely used open-source library (see Libraries & Middleware).

Tip: Keep conditions and actions small and named for designers: "can see player", "move to cover", "reload". The tree itself should read like the design document. If a leaf needs a paragraph to explain, split it.

Test yourself

A Sequence ticks children A, B, C. A returns Success and B returns Running. What does the Sequence return, and is C ticked?

  1. Success; C is ticked
  2. Running; C is not ticked
  3. Failure; C is not ticked
  4. Running; C is ticked

Why is the leftmost branch of the root selector the highest priority?

  1. Because it's drawn first
  2. Because the selector ticks children left to right and stops at the first one that doesn't fail
  3. Because it has the most nodes
  4. Because of alphabetical order

What makes a behavior tree react when the player suddenly appears?

  1. A transition must be added
  2. The tree is re-evaluated from the root every tick, so a higher-priority branch can take over
  3. Conditions return Running
  4. The blackboard is cleared