TExcelTAD
Home › Game AI › Utility AI

Utility AI

State machines and behavior trees answer "what should I do?" with rules: if this, then that. That works when there is one obvious right answer. It struggles when an agent has several competing needs at once: a survival-game deer that is a bit hungry, quite tired and has just heard a wolf. Rules like "if hunger > 0.7 and no threat and not tired…" multiply fast. Utility AI replaces the rules with scores: every possible action computes how useful it is right now, as a number from 0 to 1, and the agent does the best one. The Sims is the famous example; many strategy, survival and shooter games use utility scoring for target selection and tactics.

Considerations and response curves

Each action's score is built from considerations. A consideration takes one input (hunger, distance to enemy, own health, ammo), normalizes it to 0..1, and passes it through a response curve that expresses how much that input should matter:

Curve Formula (x in 0..1) Feels like
Linear x proportional
Quadratic x² ignores small values, urgent when high (hunger)
Inverse 1 - x the less, the better (distance to a pickup)
Logistic 1 / (1 + e^(-k(x - m))) a soft switch around m (panic once health drops below ~30%)
Step x >= m ? 1 : 0 a hard requirement ("has ammo")

The considerations of one action are multiplied, so any consideration at 0 vetoes the action (no ammo → "shoot" scores 0 however good the target is).

A utility brain in C#

The deer has three needs and five actions. Each action lists its considerations; the brain scores every action and picks the highest.

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

static double Linear(double x) => x;
static double Quad(double x) => x * x;
static double Inverse(double x) => 1 - x;
static double Logistic(double x, double mid, double k = 12) => 1 / (1 + Math.Exp(-k * (x - mid)));

var actions = new List<UtilityAction>
{
    new("Eat",    s => new[] { Quad(s.Hunger), Inverse(s.Threat) }),
    new("Sleep",  s => new[] { Quad(s.Fatigue), Inverse(s.Threat), Inverse(s.Hunger * 0.5) }),
    new("Flee",   s => new[] { Logistic(s.Threat, 0.5) }),
    new("Graze",  s => new[] { Linear(s.Hunger) * 0.5 + 0.1, Inverse(s.Threat) }),
    new("Idle",   s => new[] { 0.15 }),
};

var situations = new (string name, Situation s)[]
{
    ("calm morning",       new Situation(Hunger: 0.3, Fatigue: 0.1, Threat: 0.0)),
    ("very hungry",        new Situation(Hunger: 0.9, Fatigue: 0.4, Threat: 0.0)),
    ("exhausted",          new Situation(Hunger: 0.3, Fatigue: 0.9, Threat: 0.1)),
    ("hungry, wolf heard", new Situation(Hunger: 0.9, Fatigue: 0.4, Threat: 0.45)),
    ("wolf close",         new Situation(Hunger: 0.9, Fatigue: 0.4, Threat: 0.8)),
};

Console.WriteLine(
quot;{"situation",-20}" + string.Concat(actions.Select(a =>
quot;{a.Name,7}")) + " choice"); foreach (var (name, s) in situations) { var scores = actions.Select(a => a.Score(s)).ToList(); int best = scores.IndexOf(scores.Max()); Console.WriteLine(
quot;{name,-20}" + string.Concat(scores.Select(v =>
quot;{v,7:F2}")) +
quot; {actions[best].Name}"); } record Situation(double Hunger, double Fatigue, double Threat); record UtilityAction(string Name, Func<Situation, double[]> Considerations) { public double Score(Situation s) => Considerations(s).Aggregate(1.0, (acc, c) => acc * Math.Clamp(c, 0, 1)); }
situation               Eat  Sleep   Flee  Graze   Idle   choice
calm morning           0.09   0.01   0.00   0.25   0.15   Graze
very hungry            0.81   0.09   0.00   0.55   0.15   Eat
exhausted              0.08   0.62   0.01   0.23   0.15   Sleep
hungry, wolf heard     0.45   0.05   0.35   0.30   0.15   Eat
wolf close             0.16   0.02   0.97   0.11   0.15   Flee

The interesting row is "hungry, wolf heard": hunger is high enough that eating (0.45) still beats fleeing (0.35), so the deer keeps eating nervously. When the wolf comes close, the logistic flee curve jumps to 0.97 and overrides everything. Read the table row by row and see how the choice shifts smoothly as the inputs change, with no rule anywhere saying "if hungry and not threatened, eat". A designer tunes the curves (make hunger urgent sooner, make the deer braver) and the behaviour follows.

Note: Multiplying many considerations drags scores down: five considerations of 0.9 give 0.59, while one gives 0.9. Actions with more considerations are unfairly penalized. A common fix (from Dave Mark's Infinite Axis Utility System talks) is a compensation factor that scales each consideration up based on how many there are. Keep the number of considerations per action similar, or apply such a correction.

Commitment: stop the dithering

A pure "highest score wins" brain can switch actions every tick when two scores are close: it starts eating, its hunger drops a little, it starts sleeping, its fatigue drops a little, it starts eating again. Players see an agent that can't make up its mind. The fixes:

  • Inertia (momentum) bonus: multiply the score of the current action by, say, 1.25, so a rival must be clearly better to take over.
  • Minimum commitment time: once started, an action runs for at least N seconds unless something urgent (a high-priority "Flee") interrupts.
  • Choose from the top few instead of always the best: pick weighted-randomly among actions within 10–20% of the best score (with a seeded generator) for variety between agents.
csharp · try it yourself
using System;

// Two needs that each tick drop while being served and rise otherwise.
foreach (double bonus in new[] { 1.0, 1.25 })
{
    double hunger = 0.60, fatigue = 0.58;
    string current = "", log = "";
    int switches = 0;
    for (int t = 0; t < 12; t++)
    {
        double eat = hunger * (current == "E" ? bonus : 1);
        double sleep = fatigue * (current == "S" ? bonus : 1);
        string next = eat >= sleep ? "E" : "S";
        if (next != current && current != "") switches++;
        current = next;
        log += current;
        if (current == "E") { hunger -= 0.05; fatigue += 0.02; }
        else { fatigue -= 0.05; hunger += 0.02; }
    }
    Console.WriteLine(
quot;inertia x{bonus:F2}: {log} switches: {switches}"); }
inertia x1.00: ESESESESESES  switches: 11
inertia x1.25: EEESSSSSEEEE  switches: 2

Without inertia the agent alternates every single tick. A 25% bonus turns that into three long, believable stretches.

Where utility fits

Utility scoring rarely runs the whole agent alone. Common combinations:

Combination How
Behavior tree + utility a "utility selector" composite picks the child with the highest score instead of the first that succeeds
FSM + utility the scores decide which state to enter; states handle the details
Utility for targets and positions score every visible enemy (distance, threat, health) or every cover point; see Cover Points. Unreal's EQS is a utility system for positions; see Unreal: EQS, StateTree & Perception

Tip: Log the full score table for the selected agent, as the example does, and show it on screen in debug builds. Utility AI is easy to tune when you can see why an action won, and nearly impossible when you can't.

Test yourself

Why are an action's considerations usually multiplied rather than added?

  1. Multiplication is faster
  2. Any consideration at 0 then vetoes the action
  3. Addition can't produce values between 0 and 1
  4. To make scores larger

Which response curve fits 'barely matters until it's urgent' (such as hunger)?

  1. Inverse
  2. Quadratic (x²)
  3. Constant
  4. Linear

What does an inertia bonus on the current action prevent?

  1. Fleeing
  2. Dithering: switching back and forth when two scores are close
  3. Scores above 1
  4. Using response curves