AIController, NavMesh & Perception
AI in Unreal follows the same will/body split as players: an AAIController possesses a pawn and decides what it does. The controller brings the AI building blocks with it:
| Piece | Job |
|---|---|
AAIController |
possesses the pawn; runs a Behavior Tree or StateTree; issues move requests |
NavMesh (ARecastNavMesh, built from a Nav Mesh Bounds Volume) |
the walkable surface; pathfinding with A* over its polygons |
UPathFollowingComponent |
follows a found path, handles arrival and blockage |
UAIPerceptionComponent + sense configs |
sight, hearing, damage, team senses; reports what the AI noticed |
UBlackboardComponent |
the AI's memory: key/value pairs read by Behavior Trees |
| EQS | queries such as "find a cover point near me, out of the player's sight" (lesson EQS & StateTree) |
Add "AIModule", "NavigationSystem" and "GameplayTasks" to Build.cs.
Editor steps: navigation
- Place Actors → Volumes → Nav Mesh Bounds Volume, scale it over the playable area.
- Press P in the viewport to show the NavMesh (green). Gaps in the green are places the AI can't walk.
- Tune the agent in Project Settings → Navigation Mesh (cell size, agent radius/height, max step height) and Navigation System (runtime generation: Static, Dynamic Modifiers Only or Dynamic if level geometry moves).
- On the enemy pawn class, set Auto Possess AI = Placed in World or Spawned and AI Controller Class = your controller. Otherwise spawned enemies stand still with no controller.
An AIController with sight
// ArenaAIController.h
#pragma once
#include "CoreMinimal.h"
#include "AIController.h"
#include "Perception/AIPerceptionTypes.h"
#include "ArenaAIController.generated.h"
class UAISenseConfig_Sight;
class UBehaviorTree;
UCLASS()
class ARENA_API AArenaAIController : public AAIController
{
GENERATED_BODY()
public:
AArenaAIController();
protected:
virtual void OnPossess(APawn* InPawn) override;
UFUNCTION()
void HandleTargetPerceptionUpdated(AActor* Actor, FAIStimulus Stimulus);
UPROPERTY(EditDefaultsOnly, Category = "AI")
TObjectPtr<UBehaviorTree> BehaviorTree;
UPROPERTY(VisibleAnywhere, Category = "AI")
TObjectPtr<UAISenseConfig_Sight> SightConfig;
};// ArenaAIController.cpp
#include "ArenaAIController.h"
#include "BehaviorTree/BlackboardComponent.h"
#include "Perception/AIPerceptionComponent.h"
#include "Perception/AISenseConfig_Sight.h"
AArenaAIController::AArenaAIController()
{
SetPerceptionComponent(*CreateDefaultSubobject<UAIPerceptionComponent>(TEXT("Perception")));
SightConfig = CreateDefaultSubobject<UAISenseConfig_Sight>(TEXT("Sight"));
SightConfig->SightRadius = 1500.f;
SightConfig->LoseSightRadius = 1800.f; // larger: hysteresis
SightConfig->PeripheralVisionAngleDegrees = 60.f; // half-angle of the cone
SightConfig->DetectionByAffiliation.bDetectEnemies = true;
SightConfig->DetectionByAffiliation.bDetectNeutrals = true; // without a team setup, players count as neutral
SightConfig->SetMaxAge(5.f); // forget a stimulus after 5 s
GetPerceptionComponent()->ConfigureSense(*SightConfig);
GetPerceptionComponent()->SetDominantSense(SightConfig->GetSenseImplementation());
}
void AArenaAIController::OnPossess(APawn* InPawn)
{
Super::OnPossess(InPawn);
GetPerceptionComponent()->OnTargetPerceptionUpdated.AddDynamic(this, &AArenaAIController::HandleTargetPerceptionUpdated);
if (BehaviorTree)
{
RunBehaviorTree(BehaviorTree); // also creates the blackboard from the tree's asset
}
}
void AArenaAIController::HandleTargetPerceptionUpdated(AActor* Actor, FAIStimulus Stimulus)
{
UBlackboardComponent* BB = GetBlackboardComponent();
if (!BB || !Actor || !Actor->ActorHasTag(TEXT("Player"))) return;
if (Stimulus.WasSuccessfullySensed())
{
BB->SetValueAsObject(TEXT("TargetActor"), Actor);
}
else
{
BB->ClearValue(TEXT("TargetActor"));
BB->SetValueAsVector(TEXT("LastKnownLocation"), Stimulus.StimulusLocation);
}
}Moving without a Behavior Tree is one call: MoveToActor(Target, /*AcceptanceRadius*/ 150.f) or MoveToLocation(Point). They return an EPathFollowingRequestResult, and ReceiveMoveCompleted / OnMoveCompleted reports arrival.
Debugging: press the apostrophe key (') during play to open the Gameplay Debugger. Numpad keys toggle categories: Behavior Tree, Perception (draws the sight cone), EQS, Navigation.
A model of sight perception
Sight is a range check, a cone check (a dot product) and a line-of-sight trace, run on a time budget across all AIs. The model checks a target walking past a guard, with a pillar blocking the view at one point. Note the separate lose sight radius: once seen, the target stays seen until it is farther than 1800, not 1500.
#include <cmath>
#include <iostream>
#include <iomanip>
#include <vector>
struct V2 { double x, y; };
double Dot(V2 a, V2 b) { return a.x * b.x + a.y * b.y; }
double Len(V2 a) { return std::sqrt(Dot(a, a)); }
// Does segment a-b pass through a circle (a pillar)?
bool Blocked(V2 a, V2 b, V2 c, double r) {
V2 ab{b.x - a.x, b.y - a.y}, ac{c.x - a.x, c.y - a.y};
double t = std::fmax(0, std::fmin(1, Dot(ac, ab) / Dot(ab, ab)));
V2 p{a.x + ab.x * t - c.x, a.y + ab.y * t - c.y};
return Len(p) < r;
}
int main() {
std::cout << std::fixed << std::setprecision(0);
const V2 guard{0, 0}, forward{1, 0}; // facing +X
const double sight = 1500, loseSight = 1800, halfAngle = 60;
const V2 pillar{600, 300};
const double pillarR = 80;
std::vector<V2> path = {{1700, 900}, {1100, 800}, {1650, 0}, {1900, 0}, {1650, 0}, {900, 300}, {1000, 500}, {200, 900}, {-300, 300}};
bool seen = false;
for (V2 p : path) {
V2 to{p.x - guard.x, p.y - guard.y};
double dist = Len(to);
double angle = std::acos(Dot(to, forward) / dist) * 180 / 3.14159265358979;
bool inRange = dist <= (seen ? loseSight : sight);
bool inCone = angle <= halfAngle;
bool los = !Blocked(guard, p, pillar, pillarR);
bool now = inRange && inCone && los;
std::cout << "target (" << std::setw(5) << p.x << ", " << std::setw(4) << p.y << ") dist " << std::setw(4) << dist
<< " angle " << std::setw(3) << angle << ": " << (now ? "SEEN" : !inRange ? "out of range" : !inCone ? "outside cone" : "blocked by pillar");
if (now != seen) std::cout << (now ? " -> OnTargetPerceptionUpdated(sensed)" : " -> OnTargetPerceptionUpdated(lost)");
std::cout << "\n";
seen = now;
}
}target ( 1700, 900) dist 1924 angle 28: out of range
target ( 1100, 800) dist 1360 angle 36: SEEN -> OnTargetPerceptionUpdated(sensed)
target ( 1650, 0) dist 1650 angle 0: SEEN
target ( 1900, 0) dist 1900 angle 0: out of range -> OnTargetPerceptionUpdated(lost)
target ( 1650, 0) dist 1650 angle 0: out of range
target ( 900, 300) dist 949 angle 18: SEEN -> OnTargetPerceptionUpdated(sensed)
target ( 1000, 500) dist 1118 angle 27: blocked by pillar -> OnTargetPerceptionUpdated(lost)
target ( 200, 900) dist 922 angle 77: outside cone
target ( -300, 300) dist 424 angle 135: outside cone
The target at (1650, 0) is seen the first time (it was already seen, so the 1800 lose-sight radius applies) and not the second time (it had been lost, so it must come within 1500 again). At (1000, 500) the line to the target passes through the pillar, so sight is lost although the target is close and in front.
Test yourself
Spawned enemies stand still while placed ones work. What is a likely cause?
- No NavMesh
- Auto Possess AI is set to 'Placed in World' only
- Perception is off
- The Behavior Tree has no root
Why is LoseSightRadius larger than SightRadius?
- It is a bug
- Hysteresis: a target at the edge doesn't flicker between seen and lost
- To save performance
- For hearing
How do you see the NavMesh in the editor viewport?
- Press P
- Press F8
- Run stat nav
- Open World Settings