tutoriales.com

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.

Intermedio15 min de lectura119 views
Reportar error

🚀 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.

💡 Tip: Familiarity with Unreal Engine's **Blueprint** concepts is very helpful before tackling this tutorial.

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

  1. Create a new Unreal Engine project: Use the Third Person or First Person template to have a basic player and level.
  2. Create an Enemy Character Blueprint:
    • Right-click in the Content Browser > Blueprint Class.
    • Select Character as the parent class and name it BP_EnemyCharacter.
    • Open BP_EnemyCharacter and assign a Mesh (e.g., SK_Mannequin) and an Anim Blueprint (ABP_Manny or ABP_Quinn_C) to the Skeletal Mesh Component.
    • Adjust the collision capsule and Mesh position if necessary.
📌 Note: Make sure your `BP_EnemyCharacter` has a `Character Movement Component` so it can move correctly.

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.

  1. Create an AI Controller for the Enemy:

    • Right-click in the Content Browser > Blueprint Class.
    • Search for AIController and select it. Name it AIC_Enemy.
  2. Create a Blackboard Asset:

    • Right-click in the Content Browser > Artificial Intelligence > Blackboard.
    • Name it BB_Enemy.
    • Open BB_Enemy and 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.
  3. Assign the AI Controller to the Enemy Character:

    • Open BP_EnemyCharacter.
    • In the Details panel, search for Pawn and in the AI Controller Class section, select AIC_Enemy.
    • Set Auto Possess AI to Placed in World or Spawned.

🧠 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

  1. Create a Behavior Tree Asset:

    • Right-click in the Content Browser > Artificial Intelligence > Behavior Tree.
    • Name it BT_Enemy.
  2. Assign the Blackboard to the Behavior Tree:

    • Open BT_Enemy.
    • In the Details panel, find Blackboard Asset and select BB_Enemy.
  3. Basic Behavior Tree Structure:

    • The root node is Root.
    • From Root, drag and drop to create a Selector node. Selectors attempt to execute their children from left to right and stop at the first one that succeeds. If one of its children succeeds, the Selector also succeeds. If all its children fail, the Selector fails.
    • From the Selector, drag and drop to create two Sequence nodes. Sequences execute their children from left to right and stop if one fails. If all their children succeed, the Sequence succeeds.
Root Selector (?) Sequence 1 (→) Sequence 2 (→)

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.

  1. Create a Blueprint Service:

    • Right-click in the Content Browser > Blueprint Class.
    • Search for BTService_BlueprintBase and select it. Name it BTS_CheckForPlayer.
  2. Logic for the BTS_CheckForPlayer Service:

    • Open BTS_CheckForPlayer.
    • Override the Receive Tick AI function.
    • From Owner Controller (of the Receive Tick AI node), drag and drop to get Get Controlled Pawn. Connect it to SelfActor in the Blackboard (Set Blackboard Value as Object).
    • From Get Controlled Pawn, get Get Actor Location.
    • From Get Controlled Pawn, get Get Player Character and then Get Actor Location for the player.
    • Use a LineTraceByChannel (or LineTraceForObjects) from the enemy's location to the player's location. Channel: Visibility.
    • If the Line Trace hits the player (compare the Hit Actor with Get Player Character), then we have line of sight.
    • Set the TargetActor key in the Blackboard with Get Player Character if detected.
    • Set the HasLineOfSight key in the Blackboard based on the Line Trace result.
    • Use a Branch to decide whether to set TargetActor or clear it (if the player is not visible or too far).
  3. Add the Service to the Behavior Tree:

    • Open BT_Enemy.
    • Select the Root node (or the main Selector).
    • In the Details panel, click Add Service and select BTS_CheckForPlayer.
    • Adjust the service's update frequency (Interval). For example, 0.5 seconds.

Step 5: Implementing Player Pursuit

Now that we can detect the player, we'll make the enemy chase them.

  1. First Sequence (Chase Player):
    • In BT_Enemy, select the first Sequence.
    • Add a Blackboard Decorator to the Sequence. Configure it to succeed only if TargetActor Is Set and HasLineOfSight Is Equal to True.
    • From this Sequence, drag and drop to create a Move To task. Select TargetActor as the key.
    • From the same Sequence, drag and drop to create a Wait task (so it waits a moment before moving again, or an Attack task if you had one).

Step 6: Implementing Patrolling

If the enemy doesn't detect the player, it should patrol a series of points or a random area.

  1. Create a Blueprint Task for Patrolling:

    • Right-click in the Content Browser > Blueprint Class.
    • Search for BTTask_BlueprintBase and select it. Name it BTT_FindPatrolLocation.
  2. Logic for BTT_FindPatrolLocation:

    • Open BTT_FindPatrolLocation.
    • Override the Receive Execute AI function.
    • From Owner Controller, get Get Controlled Pawn and then Get Actor Location.
    • Use a Get Random Reachable Point in Radius (from Navigation System or directly from the Pawn if you have AI Navigation enabled) around the enemy's current location. Define a patrol radius (e.g., 1000 units).
    • If a valid location is found, set the LocationToMoveTo key in the Blackboard.
    • Call Finish Execute with success or failure depending on whether a location was found.
  3. Second Sequence (Patrol):

    • In BT_Enemy, select the second Sequence.
    • Add a Blackboard Decorator to the Sequence. Configure it to succeed only if TargetActor Is Not Set.
    • From this Sequence, drag and drop to create a BTT_FindPatrolLocation task.
    • From the same Sequence, drag and drop to create a Move To task. Select LocationToMoveTo as the key.
    • From the same Sequence, drag and drop to create a Wait task. For example, Wait 3 seconds.
? Selector (Priority) → Sequence: Chase Is Player in Range? Look at Player Move to Target → Sequence: Patrol Get Next Point Walk to Point Wait (Idle) Selector Sequence Decorator Task/Action

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

  1. Create an EQS Context:

    • Right-click in the Content Browser > Blueprint Class.
    • Search for EnvQueryContext_BlueprintBase and select it. Name it EQSContext_SelfActorLocation.
    • Open EQSContext_SelfActorLocation. Override Provide Context and from Querier, get Get Controlled Pawn and then Get Actor Location. Set this location as the context's output (Resulting Location).
  2. 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 Grid generator.
        • Grid Size: 500 (or an appropriate value for your level).
        • Space Between: 200.
        • Center: Select EQSContext_SelfActorLocation.
      • Test: Add a Pathfinding Batch test.
        • 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.

Step 8: Integrating EQS into the Behavior Tree

We'll modify the BTT_FindPatrolLocation task to use EQS.

  1. Modify BTT_FindPatrolLocation:
    • Open BTT_FindPatrolLocation.
    • Replace the Get Random Reachable Point in Radius node with a Run EQS Query node.
    • In Run EQS Query, select EQS_PatrolPoints as the Query Template.
    • Query Owner: Self.
    • Run Mode: Best Item.
    • Query Result Set BlackBoard Value: Select LocationToMoveTo.
    • Connect the output of Run EQS Query to Finish Execute with success or failure.
🔥 Important: Make sure your level has a `Nav Mesh Bounds Volume` that covers all areas where the enemy can move. Without it, navigation and EQS will not work.

🏃 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

  1. Drag an instance of BP_EnemyCharacter from the Content Browser into your level.

Step 10: Start Simulation and Debug

  1. Click Play to start the game.
  2. While the game is running, select your BP_EnemyCharacter in the World Outliner.
  3. In the editor toolbar, find the Debug button and select AI Debugger.
  4. You can also open the Behavior Tree Editor (BT_Enemy) and you'll see the execution in real-time, with active nodes highlighted.
  5. To debug EQS, open EQS_PatrolPoints and click Debug in the toolbar. You'll see the generated points and their scores.
💡 Tip: The `AI Debugger` is an invaluable tool. It allows you to see the Blackboard's state, which Behavior Tree nodes are active, and EQS information.

Possible Issues and Solutions:

  • The enemy isn't moving:
    • Verify that the Nav Mesh Bounds Volume covers the area.
    • Ensure the AI Controller is assigned and Auto Possess AI is configured.
    • Check Blackboard Decorators to make sure conditions are met.
  • The enemy isn't detecting the player:
    • Verify the BTS_CheckForPlayer logic, especially the LineTrace.
    • Make sure TargetActor is being set correctly in the Blackboard.
  • EQS isn't generating points:
    • Check that the Nav Mesh Bounds Volume is present and updated (P in the editor to visualize it).
    • Ensure EQSContext_SelfActorLocation is returning the correct location.

✨ Enhancements and Future Steps

This is just the tip of the iceberg. You can expand this AI in many ways:

  • Attack behaviors: Add an Attack task to the Behavior Tree when the player is near.
  • Defensive behaviors: Use EQS to find cover or retreat points.
  • Advanced perception: Implement AI Perception for vision, hearing detection, etc., and update the Blackboard accordingly.
  • Waypoint patrols: Create a list of Actors in 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.

Basic Component Creation: Enemy Character, AI Controller, Blackboard.
Behavior Tree Design: Defining the Patrol and Chase branches.
Detection Logic: Implementing `BTS_CheckForPlayer` to detect and track the player.
Movement Integration: `Move To` and `Find Patrol Location` tasks.
EQS Usage: Creating `EQS_PatrolPoints` to find intelligent patrol locations.
Debugging and Testing: Using the `AI Debugger` and `EQS Debugger` to refine behavior.

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

Comentarios (0)

Aún no hay comentarios. ¡Sé el primero!