Unreal Engine: Implementing Basic AI with Behavior Trees and EQS for Enemies
This tutorial will guide you through implementing basic artificial intelligence for enemies in Unreal Engine. We'll explore how to use Behavior Trees to define behavior logic and the Environmental Query System (EQS) to enable AI to make intelligent decisions within its environment. You'll learn to set up your enemy from scratch to achieve reactive behavior.
🚀 Introduction to AI in Unreal Engine with Behavior Trees and EQS
Creating compelling and challenging enemies is crucial for immersion in any video game. In Unreal Engine, we have powerful tools like Behavior Trees and the Environmental Query System (EQS) that allow us to design sophisticated and dynamic artificial intelligence without needing to write a lot of complex code. This tutorial will walk you through implementing a basic enemy AI that patrols, detects the player, and chases them.
What are Behavior Trees? 🌳
Behavior Trees provide a hierarchical and modular way to organize AI behavior logic. Think of them as a flowchart of decisions and actions that the AI executes. They allow you to build complex behaviors from smaller, more manageable units, making debugging and expansion easier.
What is the Environmental Query System (EQS)? 🗺️
EQS is an environment query system that allows AI to evaluate the game world and make informed decisions. For example, it can find the best cover, a flanking position, or determine if an area is safe. EQS uses 'generators' and 'tests' to score locations and objects in the environment, returning the best results for the AI to act upon.
🛠️ Initial Project and AI Actor Setup
Before diving into the logic, we need to set up our project and the character that will serve as the enemy.
Step 1: Create a New Project and Basic Character
- Create a new Unreal Engine project: Use the
Third PersonorFirst Persontemplate to have a basic player and level. - Create an Enemy Character Blueprint:
- Right-click in the
Content Browser>Blueprint Class. - Select
Characteras the parent class and name itBP_EnemyCharacter. - Open
BP_EnemyCharacterand assign aMesh(e.g.,SK_Mannequin) and anAnim Blueprint(ABP_MannyorABP_Quinn_C) to theSkeletal Mesh Component. - Adjust the collision capsule and
Meshposition if necessary.
- Right-click in the
Step 2: Create the AI Controller and Blackboard
The AI needs a controller to execute its logic and a Blackboard to store the data it will use. The Blackboard is essentially a scratchpad where the AI writes and reads information.
-
Create an AI Controller for the Enemy:
- Right-click in the
Content Browser>Blueprint Class. - Search for
AIControllerand select it. Name itAIC_Enemy.
- Right-click in the
-
Create a Blackboard Asset:
- Right-click in the
Content Browser>Artificial Intelligence>Blackboard. - Name it
BB_Enemy. - Open
BB_Enemyand add the following keys:TargetActor(Type:Object, Class:Actor) - To store the player reference.SelfActor(Type:Object, Class:Actor) - To store the enemy's own reference.LocationToMoveTo(Type:Vector) - To store the location the enemy should move to.HasLineOfSight(Type:Boolean) - To know if the enemy has line of sight with the player.
- Right-click in the
-
Assign the AI Controller to the Enemy Character:
- Open
BP_EnemyCharacter. - In the
Detailspanel, search forPawnand in theAI Controller Classsection, selectAIC_Enemy. - Set
Auto Possess AItoPlaced in World or Spawned.
- Open
🧠 Creating the Behavior Tree
The Behavior Tree will be the core of our enemy's logic. We'll define how it patrols, detects, and chases the player.
Step 3: Create the Behavior Tree
-
Create a Behavior Tree Asset:
- Right-click in the
Content Browser>Artificial Intelligence>Behavior Tree. - Name it
BT_Enemy.
- Right-click in the
-
Assign the Blackboard to the Behavior Tree:
- Open
BT_Enemy. - In the
Detailspanel, findBlackboard Assetand selectBB_Enemy.
- Open
-
Basic Behavior Tree Structure:
- The root node is
Root. - From
Root, drag and drop to create aSelectornode.Selectorsattempt to execute their children from left to right and stop at the first one that succeeds. If one of its children succeeds, theSelectoralso succeeds. If all its children fail, theSelectorfails. - From the
Selector, drag and drop to create twoSequencenodes.Sequencesexecute their children from left to right and stop if one fails. If all their children succeed, theSequencesucceeds.
- The root node is
Basic Behavior Tree Structure: Root, Selector, and two Sequences.
Step 4: Implementing Player Detection
Our enemy needs to be able to detect the player. We'll use a Service to constantly check for the player's presence and line of sight.
-
Create a Blueprint Service:
- Right-click in the
Content Browser>Blueprint Class. - Search for
BTService_BlueprintBaseand select it. Name itBTS_CheckForPlayer.
- Right-click in the
-
Logic for the
BTS_CheckForPlayerService:- Open
BTS_CheckForPlayer. - Override the
Receive Tick AIfunction. - From
Owner Controller(of theReceive Tick AInode), drag and drop to getGet Controlled Pawn. Connect it toSelfActorin the Blackboard (Set Blackboard Value as Object). - From
Get Controlled Pawn, getGet Actor Location. - From
Get Controlled Pawn, getGet Player Characterand thenGet Actor Locationfor the player. - Use a
LineTraceByChannel(orLineTraceForObjects) from the enemy's location to the player's location. Channel:Visibility. - If the
Line Tracehits the player (compare theHit ActorwithGet Player Character), then we have line of sight. - Set the
TargetActorkey in the Blackboard withGet Player Characterif detected. - Set the
HasLineOfSightkey in the Blackboard based on theLine Traceresult. - Use a
Branchto decide whether to setTargetActoror clear it (if the player is not visible or too far).
- Open
-
Add the Service to the Behavior Tree:
- Open
BT_Enemy. - Select the
Rootnode (or the mainSelector). - In the
Detailspanel, clickAdd Serviceand selectBTS_CheckForPlayer. - Adjust the service's update frequency (
Interval). For example,0.5seconds.
- Open
Step 5: Implementing Player Pursuit
Now that we can detect the player, we'll make the enemy chase them.
- First
Sequence(Chase Player):- In
BT_Enemy, select the firstSequence. - Add a
Blackboard Decoratorto theSequence. Configure it to succeed only ifTargetActorIs Set andHasLineOfSightIs Equal to True. - From this
Sequence, drag and drop to create aMove Totask. SelectTargetActoras the key. - From the same
Sequence, drag and drop to create aWaittask (so it waits a moment before moving again, or anAttacktask if you had one).
- In
Step 6: Implementing Patrolling
If the enemy doesn't detect the player, it should patrol a series of points or a random area.
-
Create a Blueprint Task for Patrolling:
- Right-click in the
Content Browser>Blueprint Class. - Search for
BTTask_BlueprintBaseand select it. Name itBTT_FindPatrolLocation.
- Right-click in the
-
Logic for
BTT_FindPatrolLocation:- Open
BTT_FindPatrolLocation. - Override the
Receive Execute AIfunction. - From
Owner Controller, getGet Controlled Pawnand thenGet Actor Location. - Use a
Get Random Reachable Point in Radius(fromNavigation Systemor directly from thePawnif you haveAI Navigationenabled) around the enemy's current location. Define a patrol radius (e.g., 1000 units). - If a valid location is found, set the
LocationToMoveTokey in the Blackboard. - Call
Finish Executewith success or failure depending on whether a location was found.
- Open
-
Second
Sequence(Patrol):- In
BT_Enemy, select the secondSequence. - Add a
Blackboard Decoratorto theSequence. Configure it to succeed only ifTargetActorIs Not Set. - From this
Sequence, drag and drop to create aBTT_FindPatrolLocationtask. - From the same
Sequence, drag and drop to create aMove Totask. SelectLocationToMoveToas the key. - From the same
Sequence, drag and drop to create aWaittask. For example,Wait3 seconds.
- In
Visual representation of the Behavior Tree structure for chasing and patrolling.
🌍 Enhancing Decision-Making with EQS
EQS will allow us to find more intelligent patrol points, cover, or flanking positions for the player. For this tutorial, we'll use it to find a random and accessible patrol point.
Step 7: Creating an EQS Query for Patrol Points
-
Create an EQS Context:
- Right-click in the
Content Browser>Blueprint Class. - Search for
EnvQueryContext_BlueprintBaseand select it. Name itEQSContext_SelfActorLocation. - Open
EQSContext_SelfActorLocation. OverrideProvide Contextand fromQuerier, getGet Controlled Pawnand thenGet Actor Location. Set this location as the context's output (Resulting Location).
- Right-click in the
-
Create an EQS Query:
- Right-click in the
Content Browser>Artificial Intelligence>Environment Query. - Name it
EQS_PatrolPoints. - Open
EQS_PatrolPoints.- Generator: Add a
Simple Gridgenerator.Grid Size: 500 (or an appropriate value for your level).Space Between: 200.Center: SelectEQSContext_SelfActorLocation.
- Test: Add a
Pathfinding Batchtest.Context:EQSContext_SelfActorLocation.Query Param:Item.Score Multiplier: 1.Scoring Equation:Linear.Weight: 1.- This ensures that the generated points are accessible by the enemy.
- Generator: Add a
- Right-click in the
Step 8: Integrating EQS into the Behavior Tree
We'll modify the BTT_FindPatrolLocation task to use EQS.
- Modify
BTT_FindPatrolLocation:- Open
BTT_FindPatrolLocation. - Replace the
Get Random Reachable Point in Radiusnode with aRun EQS Querynode. - In
Run EQS Query, selectEQS_PatrolPointsas theQuery Template. Query Owner:Self.Run Mode:Best Item.Query Result Set BlackBoard Value: SelectLocationToMoveTo.- Connect the output of
Run EQS QuerytoFinish Executewith success or failure.
- Open
🏃 Running and Debugging the AI
Once everything is set up, it's time to test and debug.
Step 9: Place the Enemy in the Level
- Drag an instance of
BP_EnemyCharacterfrom theContent Browserinto your level.
Step 10: Start Simulation and Debug
- Click
Playto start the game. - While the game is running, select your
BP_EnemyCharacterin theWorld Outliner. - In the editor toolbar, find the
Debugbutton and selectAI Debugger. - You can also open the
Behavior Tree Editor(BT_Enemy) and you'll see the execution in real-time, with active nodes highlighted. - To debug EQS, open
EQS_PatrolPointsand clickDebugin the toolbar. You'll see the generated points and their scores.
Possible Issues and Solutions:
- The enemy isn't moving:
- Verify that the
Nav Mesh Bounds Volumecovers the area. - Ensure the
AI Controlleris assigned andAuto Possess AIis configured. - Check
Blackboard Decoratorsto make sure conditions are met.
- Verify that the
- The enemy isn't detecting the player:
- Verify the
BTS_CheckForPlayerlogic, especially theLineTrace. - Make sure
TargetActoris being set correctly in the Blackboard.
- Verify the
- EQS isn't generating points:
- Check that the
Nav Mesh Bounds Volumeis present and updated (Pin the editor to visualize it). - Ensure
EQSContext_SelfActorLocationis returning the correct location.
- Check that the
✨ Enhancements and Future Steps
This is just the tip of the iceberg. You can expand this AI in many ways:
- Attack behaviors: Add an
Attacktask to the Behavior Tree when the player is near. - Defensive behaviors: Use EQS to find cover or retreat points.
- Advanced perception: Implement
AI Perceptionfor vision, hearing detection, etc., and update the Blackboard accordingly. - Waypoint patrols: Create a list of
Actorsin the level and have the AI visit them sequentially. - AI States: Implement states like
Idle,Patrol,Chase,Attack,Flee, and transitions between them using decorators and services. - Complex interactions: Allow enemies to communicate with each other or react to world events.
FAQ: Frequently Asked Questions about AI in Unreal Engine
Q: Is it better to use Blueprints or C++ for AI? A: For basic to medium-complexity AI, Blueprints are excellent due to their rapid iteration and visibility. For very complex logic or performance optimization in large games, C++ might be preferable. Often, a combination is used: core logic in Blueprints and very specific or low-level tasks in C++.
Q: What's the difference between a Service and a Task in a Behavior Tree?
A: A Task is an action the AI performs (e.g., Move, Attack). A Service is a task that runs repeatedly while its branch of the tree is active, often to update the Blackboard or check conditions (e.g., Check if the player is visible).
Q: What is a Decorator?
R: Decorators are conditions that determine if a branch of the Behavior Tree can execute. They act like gates that open or close based on Blackboard data or other conditions.
With these foundations, you have a solid starting point for creating enemies with complex and engaging behaviors in your Unreal Engine games. Experiment and have fun building your own legion of AIs!
Tutoriales relacionados
- Unreal Engine: Creación de un Sistema de Diálogos Ramificados con Data Tables y Blueprintintermediate15 min
- Unreal Engine: Creando un Sistema de Inventario Dinámico con UMG y C++intermediate25 min
- Unreal Engine: Creando Interactividad con el Sistema de Interacciones Basado en Componentesintermediate15 min
- Dominando el Sistema de Animación en Unreal Engine 5: Desde Retargeting hasta Blend Spacesintermediate20 min
Comentarios (0)
Aún no hay comentarios. ¡Sé el primero!