Skip to content
Tutorials Center
My learning

Topics

Lesson 37 of 38 ยท Projects and Practice

Project: A Patrolling Enemy

Build a patrolling enemy in Unreal Engine that spots the player and chases. AI Controller, patrol points, perception, behavior tree, health component and a Python model of the logic.

In this project you add a threat to your level: an enemy that patrols between waypoints, notices the player by sight, chases, attacks in range and gives up if it loses the player. It brings together behavior trees, AI perception and navigation, animation state machines and delegates.

The Unreal Editor is not available on this site, so the steps are exact instructions for your own editor and the C++ is read-only. A Python model lets you test the behavior logic first. Written for Unreal Engine 5.x using the Third Person template (the project from A collectible coin game works as a base).

Design first

Write the behavior in plain words before touching the editor:

  1. Patrol: walk to each waypoint in order, wait 2 seconds, go to the next, loop.
  2. Chase: if the player is seen, run to the player.
  3. Attack: if within 150 cm of the player, hit once per second.
  4. Search: if the player is lost, go to the last known position, wait 3 seconds, then resume patrolling.

Four behaviors give four branches in the tree. Priority order: attack, chase, search, patrol.

Step 1: the enemy pawn

Duplicate the third-person Character Blueprint or create a Character subclass BP_Enemy:

  • Set Auto Possess AI to Placed in World or Spawned.
  • Set AI Controller Class to EnemyAIController (created below).
  • Set the Character Movement > Max Walk Speed to 200 for patrol; the AI will raise it to 450 when chasing.
  • Use a different material instance so the enemy is easy to tell apart.

Step 2: patrol points

Create a C++ Actor PatrolRoute with a TArray<TObjectPtr<AActor>> or a TArray<FVector> exposed with meta = (MakeEditWidget = true) so the points can be moved in the viewport as gizmos:

C++
UPROPERTY(EditAnywhere, Category = "Patrol", meta = (MakeEditWidget = true))
TArray<FVector> Points;

FVector GetWorldPoint(int32 Index) const
{
    return GetActorTransform().TransformPosition(Points[Index % Points.Num()]);
}

On the enemy add UPROPERTY(EditInstanceOnly) TObjectPtr<APatrolRoute> Route;, and on the controller a PatrolIndex integer. Placed enemies can then be assigned a route in the level.

Step 3: the AI controller

C++
AEnemyAIController::AEnemyAIController()
{
    Perception = CreateDefaultSubobject<UAIPerceptionComponent>(TEXT("Perception"));
    auto* Sight = CreateDefaultSubobject<UAISenseConfig_Sight>(TEXT("Sight"));
    Sight->SightRadius = 1500.f;
    Sight->LoseSightRadius = 1800.f;
    Sight->PeripheralVisionAngleDegrees = 70.f;
    Sight->SetMaxAge(5.f);                 // forget the stimulus after 5 s
    Sight->DetectionByAffiliation.bDetectNeutrals = true;
    Sight->DetectionByAffiliation.bDetectEnemies = true;
    Sight->DetectionByAffiliation.bDetectFriendlies = true;
    Perception->ConfigureSense(*Sight);
    Perception->SetDominantSense(Sight->GetSenseImplementation());
}

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

void AEnemyAIController::OnPossess(APawn* InPawn)
{
    Super::OnPossess(InPawn);
    RunBehaviorTree(Tree);
}

void AEnemyAIController::OnSeen(AActor* Actor, FAIStimulus Stimulus)
{
    if (!Actor->IsA<ACharacter>() || !Cast<ACharacter>(Actor)->IsPlayerControlled())
    {
        return;
    }
    UBlackboardComponent* BB = GetBlackboardComponent();
    if (Stimulus.WasSuccessfullySensed())
    {
        BB->SetValueAsObject(TEXT("TargetActor"), Actor);
    }
    else
    {
        BB->SetValueAsVector(TEXT("LastKnownLocation"), Stimulus.StimulusLocation);
        BB->ClearValue(TEXT("TargetActor"));
    }
}

Create a Blackboard BB_Enemy with keys TargetActor (Object, base class Actor), LastKnownLocation (Vector) and PatrolLocation (Vector). Assign it to the behavior tree.

Step 4: the behavior tree

Create BT_Enemy with this structure (see Behavior trees and blackboards):

Text
Root (Blackboard: BB_Enemy)
โ””โ”€ Selector
   โ”œโ”€ Sequence [Blackboard: TargetActor is Set, Observer Aborts: Both]
   โ”‚   โ”œโ”€ Move To (TargetActor, acceptable radius 120)
   โ”‚   โ””โ”€ Attack Target (custom task, Cooldown decorator 1.0 s)
   โ”œโ”€ Sequence [Blackboard: LastKnownLocation is Set, Observer Aborts: Lower Priority]
   โ”‚   โ”œโ”€ Move To (LastKnownLocation)
   โ”‚   โ”œโ”€ Wait 3 s
   โ”‚   โ””โ”€ Clear Blackboard Value (LastKnownLocation)
   โ””โ”€ Sequence
       โ”œโ”€ Get Next Patrol Point (custom task, writes PatrolLocation)
       โ”œโ”€ Move To (PatrolLocation)
       โ””โ”€ Wait 2 s

The custom tasks are short Blueprint or UBTTaskNode classes. Attack Target can play an attack montage (see Blend spaces and montages) and apply damage with UGameplayStatics::ApplyDamage. Get Next Patrol Point reads the route from the pawn, increments the index and writes the vector.

Place a Nav Mesh Bounds Volume around the level and press P to check the green coverage.

Test the logic in a model

The model implements the four behaviors with a tick loop. Walk the player through the scenario and check that the enemy switches behavior as designed.

Python Stand-in: patrol, chase, search, attack

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

If the enemy never leaves Patrol in your editor build, the same questions apply: is the player inside the sight radius and cone, and is perception set to detect the player's affiliation?

Step 5: damage and health

Add a reusable Health Component (an UActorComponent with Health, ApplyDamage and an OnHealthChanged delegate, as in Delegates, timers and spawning). Attach it to both the player and the enemy. The enemy's attack calls ApplyDamage on the player's component; the HUD binds to the delegate.

Python Stand-in: damage with cooldown

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Polish and next steps

  • Switch walk speed when the target changes: slow for patrol, fast for chase.
  • Use a Blend Space driven by speed so the legs match movement.
  • Add hearing: pass ReportNoiseEvent when the player jumps or runs.
  • Add Environment Query System for finding cover or flanking.
  • Check performance with stat unit with many enemies (see Profiling and stat commands).

Common mistakes

  • Enemy stands still. No Nav Mesh, no RunBehaviorTree, or the Blackboard asset is missing from the tree.
  • Never loses interest. Perception max age is zero (stimuli never expire) or you never clear TargetActor.
  • Jittery chase. The Move To goal updates every frame; set Observe Blackboard Value to false or use a tolerance.
  • Attack plays but no damage. Apply damage from a notify at the right frame, not at task start.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why is the attack/chase branch placed leftmost in the selector?

    Priority in a behavior tree comes from child order.
  2. 2. What should happen to TargetActor when sight is lost?

    Clearing the target lets lower-priority behavior (search, then patrol) run.
  3. 3. Which component should the AI sight configuration be attached to?

    Perception belongs to the controller that owns the Blackboard and tree.
  4. 4. The enemy never moves. Which is NOT a likely cause?

    Material shininess does not affect AI; the other three prevent movement.

Summary

  • Plan behaviors and priorities in words, then map them to selector branches.
  • The AI Controller holds perception and writes to the Blackboard; the tree reads it.
  • Observer aborts make the enemy react immediately; clearing keys lets it resume patrol.
  • Test the logic in a small model, then debug in the editor with the Gameplay Debugger.

Next: Practice: Debugging Checklist and Interview Questions