TExcelTAD
Home › Game AI › Unreal: EQS, StateTree & Perception

Unreal: EQS, StateTree & Perception

The previous lesson covered the controller, behavior trees and the blackboard. Three more Unreal systems answer the questions a tree can't answer by itself:

System Question it answers Course lesson
EQS (Environment Query System) "Which spot or actor is best right now?" Cover Points, Influence Maps
AI Perception "What can I see, hear and remember?" Vision Cones, Hearing & Noise, Memory & Awareness
StateTree "Which state am I in, and when do I leave it?" Hierarchical State Machines

EQS: generate, test, score

An Environment Query asset (enable the Environment Query Editor plugin if it's off) has three kinds of parts:

  • a Generator produces candidate items: points on a grid or ring around the querier, actors of a class, navmesh points;
  • Contexts name the reference objects the tests measure against: the querier, the target actor, the last known location;
  • Tests run on every item. A test either filters (drop items that fail, such as "can the player see this point?") or scores (distance, dot product, path length), or both. Filters run first so fewer items need scoring. Each scoring test's results are normalized to 0..1 and combined with the test's weight.

A behavior tree runs a query with the Run EQS Query task and writes the winner into a blackboard key. From C++:

cpp
#include "EnvironmentQuery/EnvQueryManager.h"

void AGuardAIController::FindCover()
{
    FEnvQueryRequest Request(FindCoverQuery, GetPawn());      // UEnvQuery asset, querier
    Request.Execute(EEnvQueryRunMode::SingleResult, this, &AGuardAIController::OnCoverFound);
}

void AGuardAIController::OnCoverFound(TSharedPtr<FEnvQueryResult> Result)
{
    if (Result->IsSuccessful())
    {
        GetBlackboardComponent()->SetValueAsVector(TEXT("CoverLocation"), Result->GetItemAsLocation(0));
    }
}

Queries run asynchronously and are time-sliced by the EQS manager, so the result arrives in a later frame. Here's the same pipeline in plain C#: a 7×7 grid of points around the guard G, a trace filter that keeps only points the player P can't see past the wall, and two weighted scores.

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

string[] map =
{
    "............",
    "....#.......",
    "....#.......",
    "....#...P...",
    "....#.......",
    "............",
    "............",
};
var guard = (x: 5, y: 5);
var player = (x: 8, y: 3);

bool Wall(int x, int y) => y < 0 || y >= map.Length || x < 0 || x >= map[0].Length || map[y][x] == '#';
double Dist((int x, int y) a, (int x, int y) b) => Math.Sqrt((a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y));
bool Visible((int x, int y) a, (int x, int y) b)
{
    for (double t = 0; t <= 1; t += 0.05)                  // sample the segment (a trace)
        if (Wall((int)Math.Round(a.x + (b.x - a.x) * t), (int)Math.Round(a.y + (b.y - a.y) * t))) return false;
    return true;
}

// Generator: a grid of points around the querier.
var items = new List<(int x, int y)>();
for (int dy = -3; dy <= 3; dy++)
    for (int dx = -3; dx <= 3; dx++)
        if (!Wall(guard.x + dx, guard.y + dy)) items.Add((guard.x + dx, guard.y + dy));
Console.WriteLine(
quot;generated {items.Count} items"); // Test 1 (filter): the player must NOT see the point. items = items.Where(p => !Visible(player, p)).ToList(); Console.WriteLine(
quot;after trace filter: {items.Count} items"); // Tests 2 and 3 (score), each normalized to 0..1, then weighted. double[] Normalize(IEnumerable<double> v) { var a = v.ToArray(); double lo = a.Min(), hi = a.Max(); return a.Select(x => hi > lo ? (x - lo) / (hi - lo) : 1).ToArray(); } var nearGuard = Normalize(items.Select(p => -Dist(p, guard))); // closer to me is better var farPlayer = Normalize(items.Select(p => Dist(p, player))); // further from the player is better var scored = items.Select((p, i) => (p, score: 1.0 * nearGuard[i] + 0.5 * farPlayer[i])) .OrderByDescending(s => s.score).ThenBy(s => s.p.y).ThenBy(s => s.p.x).ToList(); foreach (var (p, score) in scored.Take(3)) Console.WriteLine(
quot; ({p.x},{p.y}) score {score:F2}"); var best = scored[0].p; for (int y = 0; y < map.Length; y++) { var row = map[y].ToCharArray(); foreach (var p in items) if (p.y == y) row[p.x] = 'o'; if (guard.y == y) row[guard.x] = 'G'; if (best.y == y) row[best.x] = '*'; Console.WriteLine(new string(row)); }
generated 32 items
after trace filter: 8 items
  (3,5) score 1.15
  (2,5) score 1.05
  (3,4) score 0.93
............
....#.......
..oo#.......
..oo#...P...
..oo#.......
..o*.G......
............

o marks every point that survived the filter and * the winner. With different weights the same query prefers different spots, which is why designers tune EQS in the editor with the EQS Testing Pawn, which draws every item and its score in the level.

AI Perception

Add a UAIPerceptionComponent to the AI controller and give it sense configs. Sight has two radii on purpose: you notice a target inside SightRadius but only lose it beyond the larger LoseSightRadius, so a player standing right at the edge doesn't flicker between seen and unseen.

cpp
AGuardAIController::AGuardAIController()
{
    Perception = CreateDefaultSubobject<UAIPerceptionComponent>(TEXT("Perception"));
    Sight = CreateDefaultSubobject<UAISenseConfig_Sight>(TEXT("Sight"));
    Sight->SightRadius = 1500.f;
    Sight->LoseSightRadius = 1900.f;
    Sight->PeripheralVisionAngleDegrees = 60.f;          // half angle: 120 degrees in total
    Sight->DetectionByAffiliation.bDetectEnemies = true;
    Sight->DetectionByAffiliation.bDetectNeutrals = true;
    Perception->ConfigureSense(*Sight);
    Perception->SetDominantSense(Sight->GetSenseImplementation());
}

void AGuardAIController::BeginPlay()
{
    Super::BeginPlay();
    Perception->OnTargetPerceptionUpdated.AddDynamic(this, &AGuardAIController::OnPerceived);
}

void AGuardAIController::OnPerceived(AActor* Actor, FAIStimulus Stimulus)   // a UFUNCTION
{
    GetBlackboardComponent()->SetValueAsObject(TEXT("TargetActor"), Stimulus.WasSuccessfullySensed() ? Actor : nullptr);
}

Hearing works the same way with UAISenseConfig_Hearing; gameplay code makes noise with UAISense_Hearing::ReportNoiseEvent(this, Location, Loudness, Instigator). Each sense config's Max Age decides how long a stimulus is remembered. The model below checks a player who walks away and comes back; the event fires only when the sensed state changes, like OnTargetPerceptionUpdated:

csharp · try it yourself
using System;

const double SightRadius = 10, LoseSightRadius = 13, HalfAngle = 60;
bool seen = false;
// (distance, angle from the guard's forward direction in degrees)
(double d, double a)[] samples = { (14, 0), (9.5, 10), (11, 5), (12.5, 0), (13.5, 0), (12, 0), (9, 100), (9, 20) };

foreach (var (d, a) in samples)
{
    double radius = seen ? LoseSightRadius : SightRadius;     // hysteresis
    bool now = d <= radius && Math.Abs(a) <= HalfAngle;
    string evt = now != seen ? (now ? "  -> perceived (event)" : "  -> lost sight (event)") : "";
    Console.WriteLine(
quot;d={d,4:F1} angle={a,3} test radius {radius,2}: {(now ? "seen" : "not seen")}{evt}"); seen = now; }
d=14.0 angle=  0 test radius 10: not seen
d= 9.5 angle= 10 test radius 10: seen  -> perceived (event)
d=11.0 angle=  5 test radius 13: seen
d=12.5 angle=  0 test radius 13: seen
d=13.5 angle=  0 test radius 13: not seen  -> lost sight (event)
d=12.0 angle=  0 test radius 10: not seen
d= 9.0 angle=100 test radius 10: not seen
d= 9.0 angle= 20 test radius 10: seen  -> perceived (event)

StateTree

StateTree (the StateTree and GameplayStateTree plugins) is a hierarchical state machine with behavior-tree-style selection. States form a tree; a state with children acts as a selector that picks the first child whose enter conditions pass. Each active state runs its tasks, and transitions fire when the state completes, succeeds or fails, on tick, or on a gameplay event. Evaluators and global tasks expose data that every state can bind to; parameters pass data in from outside.

text
Root
├── Combat            enter condition: TargetActor is valid
│   ├── Chase         task: Move To TargetActor        on completed  → Attack
│   └── Attack        task: play attack montage        on completed  → Chase
├── Investigate       enter condition: has LastKnownLocation
│                     task: Move To LastKnownLocation  on completed  → Patrol
└── Patrol            task: Move To next patrol point   on completed  → Patrol

For AI, add a StateTree AI Component (UStateTreeAIComponent) to the AI controller and pick a tree that uses the StateTree AI component schema, which gives tasks access to the controller and pawn. StateTree suits AI that is mostly "be in a mode until something happens" (most enemies, NPC routines, smart objects), while behavior trees remain strong for long priority lists with many interruptions. Both can run EQS queries and read perception.

Tip: Don't fight the tool. If your behavior tree is a selector of "modes", each with one long sequence, it's really a state machine; StateTree will be easier to read. If your state machine has transitions from everywhere to everywhere, a priority-ordered tree is clearer.

Test yourself

In an EQS query, why do filter tests run before scoring tests?

  1. Scoring tests can't see filtered items
  2. Dropping items first means fewer items need the more expensive scoring
  3. Filters are written in Blueprint
  4. The order is random

Why is LoseSightRadius larger than SightRadius?

  1. To save performance
  2. Hysteresis: a target at the edge doesn't flicker between seen and lost
  3. The AI sees further when moving
  4. It is the hearing range

In StateTree, what does a state with child states do?

  1. Runs all children at once
  2. Acts as a selector: it picks a child whose enter conditions pass
  3. Nothing; only leaves can have tasks
  4. Loops forever