Behavior Tree Quick Start Guide

The Behavior Tree Quick Start Guide walks you through the process of creating a NavMesh, creating an AI Controller, creating a Character that will be controlled by that AI Controller, and creating all the parts necessary for a simple Behavior Tree.

1 - Essential Setup

This Quick Start makes some assumptions about what is available in the project, as such, if you aren't comfortable making substitutions or problem solving on the fly, then you should setup the project as follows.

  1. Open Unreal Editor

  2. Generate a new project based on the Blueprint Top Down template

    Starter Content is optional for this quick start guide.

If you need further explanation of starting a new project, see the Project Browser User Guide.

2 - Create a Nav Mesh Bounds Volume

The NavMesh in Unreal has a number of functions that work well with Behavior Trees, and while it may not be necessary depending on the game you are making, it will help in a number of game types. Also, the Top Down template already includes a Nav Mesh Bounds Volume, but you may choose to start in a completely blank project at a later date.

Steps

  1. Modes panel > Volumes > Volumes.

  2. Click and drag a Nav Mesh Bounds Volume into the map.

  3. Translate and Scale the volume so it encapsulates the areas you want your characters to be able to navigate.

    • You can use more than one Volume if you like, or one large one that encapsulates the entire level.

  4. While working in the Viewport, press the P key to see if your NavMesh is building.

    If you see a green mesh overlay on your floors, it is building correctly. When the mesh turns red, it means it is recalculating a section because you either moved the volume or the mesh inside of it.

    You can press the P key at any time to show or hide the NavMesh.

3 - Create the Basic Assets

To start, you will need create 4 assets in the Content Browser: an AI Controller Blueprint, a Character Blueprint, a Behavior Tree Asset, and a Black Board Asset.

Steps

  1. New -> Blueprint -> AI Controller

    You will need to search for AI Controller, as they are different from Player Controller.

    Name this Blueprint "Follower_AI_CON".

  2. New -> Blueprint -> Character

    Name this Blueprint "AI_Character".

  3. New -> Artificial Intelligence -> Behavior Tree

    Name the Behavior Tree "FollowerBT".

  4. New -> Artificial Intelligence -> Blackboard.

    Name the Blackboard "FollowerBlackboard".

4 - Setup the Character Blueprint

As we have created a project with a Character already in it, we have access to a humanoid Skeletal Mesh and its Animation Blueprint. We will use these in the tutorial, but feel free to use your own if you have them available.

This Character will become our new AI Character. The reason we use a Character, over say a Pawn, is to gain access to the Character Movement Component's functionality.

Steps

  1. Double-click the AI_Character Blueprint in the Content Browser to open it for editing.

  2. Select the Mesh component in the Components panel.

  3. In the Details panel, find the Mesh category and assign the SK_Mannequin (or your own) Skeletal Mesh.

  4. Move the Mesh Component to center it up inside in the capsule.

  5. Rotate the Mesh Component so it faces the direction the blue Arrow Component is pointing.

  6. In the Details panel, find the Animation category and assign the ThirdPerson_AnimBP to the Animation Blueprint Generated Class property.

  7. Select the CapsuleComponent from the Components panel, then in the Details panel, adjust the Capsule Half Height and Capsule Radius so they encompass the Skeletal Mesh.

  8. Select the Character Movement Component.

  9. In the Details panel, in the Movement Component category, adjust the Agent Radius and Agent Height values.

    Set the Agent Radius to at least the Capsule's radius, and the Agent Height to at least twice the Capsule's "half height."

  10. With the Character Movement Component still selected, change the Max Walk Speed property, in the Character Movement category to 400.

  11. Click the Class Defaults button and assign the new AI Controller (Follower_AI_CON) to the AIController Class property in the Pawn category.

  12. Compile and Save.

5 - Setup the Blackboard Asset

The Blackboard asset stores all of the data needed for a specific instance of an AI controller that will be referenced by the Behavior Tree. In this specific case, we'll be storing an Actor to Follow (TargetToFollow), the AI's starting location (HomeLocation), and the last know location of the Actor we're following (TargetLocation).

Steps

  1. Double-click the Blackboard asset in the Content Browser.

  2. Using the New Key button, add an Object value named TargetToFollow.

  3. Add a Vector value named HomeLocation.

  4. Add a Vector value named TargetLocation.

  5. Save your Blackboard asset.

6 - Setup the AI Controller Blueprint

Using the Top Down template gives us access to mouse controls to move our character around, but for the other character we are going to create, he will need his own controller. This AI Controller is going to set a few values on its Blackboard and is going to kick off the running of our Behavior Tree. For those familiar with Blueprints, here is what the final Event Graph will look like:

Below are the steps for creating the first part of the Event Graph. Step 7. AI Controller Blueprint: Initial Blackboard Values and Step 8. AI Controller Blueprint: Run the Behavior Tree also involve editing this graph.

Steps

  1. Double-click the AI Controller Blueprint in the Content Browser to begin editing it.

  2. Using the Right-click Context menu in the Graph Panel:

    1. Add an Event Begin Play node.

    2. Add an Use Blackboard node.

  3. On the Use Blackboard node, change the Blackboard Asset to the one you created in step 3.

  4. Connect the output execution pin on the Event Begin Play node, to the input execution pin on the Use Blackboard node.

In the next step we'll continuing editing this graph and setup the initial Blackboard values for our AI Controller.

7 - AI Controller Blueprint: Initial Blackboard Values

Now we need to set the "HomeLocation" key on the Blackboard. This is a more involved step.

Steps

  1. You need a Get Blackboard node and a Get Controlled Pawn node.

  2. Get a Reference to Self node from the Right-click context menu and connect it to the Get Blackboard node.

  3. Drag off the Return Value of the Get Blackboard node, search for "Vector", and create a Set Value as Vector node.

    createSetKeyVectorNode.png
  4. Drag off the Return Value of the Get Controlled Pawn node and create a Get Actor Location node.

  5. Connect the Return Value pin of the Get Actor Location node to the Vector Value pin of the Set Value as Vector node.

  6. Drag off Key Name on the Set Value as Vector node and use Promote to Variable from the context menu.

  7. The variable should be awaiting a name in the My Blueprint panel, name the variable to HomeLocation.

    • If you clicked anywhere before naming the variable, you can rename it in the My Blueprint panel using the Right-click context menu.

  8. Compile the Blueprint.

  9. Select the HomeLocationKey variable in the My Blueprint Panel.

  10. In the Details panel, change its Default Value to the exact name of the Vector Value on the Blackboard, in this case, "HomeLocation"

  11. Connect the output execution pin of the Use Blackboard node to the input execution pin of the Set Value as Vector node.

In the next step we'll continue editing this graphs and add to this graph to make the AI Controller run the desired Behavior Tree.

8 - Controller Blueprint: Run the Behavior Tree

Finally, we just have to run our Behavior Tree with a single node.

Steps

  1. Create a Run Behavior Tree node.

  2. Set the BTAsset value to the Behavior Tree asset you created in step 3.

  3. Connect the output execution pin of the Set Value as Vector node to the input execution pin of the Run Behavior Tree node.

  4. Save your AI Controller Blueprint.

9 - Place the Character

We need to place our AI_Character into the level so it can interact with the player or environment.

Steps

  1. From the Content Browser, click and drag the AI_Character, that you created earlier, into the level.

10 - Behavior Tree Basics

The Root node starts the tree, and all other nodes connect below it.

It can only have one output connection. The darker bar on the bottom of the node is like a pin in Blueprint that you can drag off to connect to other nodes:

However, unlike Blueprint node pins which allow you to drag connections from either output to input, or input to output, Behavior Tree nodes are directional: you must drag from an "output bar" to an "input bar."

Steps

  1. Open your Behavior Tree asset, if it is not open already, by Double-clicking it in the Content Browser.

  2. In Behavior Tree mode, Right-click in the graph area and create two Composites -> Selector nodes.

  3. In Behavior Tree mode, Right-click in the graph area and create a Composites -> Sequence node.

These are the 2 primary decision making nodes available for Behavior Trees. The Selector node will run through its children, from left to right, until one of them succeeds, at which point it will fail back up the tree. While the Sequence node will run through its children from left to right until one of them fails, at which point it will fail back up the tree.

While Selector and Sequence nodes will have a number of children under them, the Root node can only have one node attached to it.

11 - Make a Service

Services attach to Composite nodes, and will execute at their defined frequency as long as their branch is being executed. These are often used to make checks and to update the Blackboard. These take the place of traditional Parallel nodes in other Behavior Tree systems

In this case, the service is going to look for any Pawn that is not an AI Character, then set the TargetToFollow and TargetLocation Blackboard keys.

Steps

  1. Open the FollowerBT Behavior Tree by Double-clicking it in the Content Browser.

  2. Click New Service button.

    It will create in the same folder as the Behavior Tree.

  3. Rename it in the Content Browser to "AgroCheck".

  4. The editor should have already opened it for editing, but if not, Double-click it in the Content Browser.

  5. Create the following graph:

    Copy Example

    Click the image to expand it, or click here to open it in the window.

    The variable names, types, and values for this Blueprint:

    Variable Name

    Type

    Default Value

    DesiredObjectTypes

    Array of type EObjectTypeQuery

    One element set to Pawn

    MyLocation

    Vector 3

    0,0,0

    AI_CON_Ref

    Follower_AI_CON_C

    None

    TargetToFollow

    BlackboardKeySelector

    None - However, this variable has its "Editable" flag set to True so you can change it, per instance, on the Behavior Tree.

    TargetLocation

    BlackboardKeySelector

    None - However, this variable has its "Editable" flag set to True so you can change it, per instance, on the Behavior Tree.

The variable DesiredObjectTypes is an Array of the type EObjectTypeQuery with a single element set to Pawn. To do this, select the DesiredObjectTypes variable in the My Blueprint panel, then in the Details Panel, under the Default Value category, click the button to add an element. Using the pull down on that element, select Pawn.

If the Default Values category doesn't show anything, Compile the Blueprint.

Here is what is going on in this graph:

  1. Event Tick works just like the same even in Actors, except it is ticked at a rate defined in the Behavior Tree.

  2. The Owner Actor passed in is always the Controller calling the Behavior Tree, so let us store that. But, only do that if we don't already have it stored, just to reduce some overhead from the cast node.

  3. Do a Multi Sphere Trace for Objects based on the location of the controlled pawn, and get all the pawns, minus the controlled pawn.

  4. The For Each loop then figures out if the player was hit.

  5. If it is, do a visibility trace to see if our AI pawn can see the player pawn.

  6. If yes, set the appropriate values on the blackboard object for the AI pawn (Target to Follow and Target Location).

  7. If no, clear the Target to Follow key on the blackboard.

12 - Make a Task

Tasks are nodes that "do" things, like move an AI, or adjust Blackboard values. They can have Decorators attached to them.

This Task is basically a re-creation of the Move To node, with one major difference: this Task will have the AI always run towards the Player's Pawn, instead of its location. Also, it helps to break things down and see that if you don't ever execute Finish Execute the Task Node will continue to process, and the AI MoveTo node shows this perfectly.

Steps

  1. Open the FollowerBT Behavior Tree by Double-clicking it in the Content Browser.

  2. Click New Task button.

    It will create in the same folder as the Behavior Tree.

  3. Rename it in the Content Browser to "RapidMoveTo".

  4. The editor should have already opened it for editing, but if not, Double-click it in the Content Browser.

  5. Create the following graph:

    Copy Example

    Click the image to expand it, or click here to open it in the window.

    The variable names, types, and values for this Blueprint:

    Variable Name

    Type

    Value

    AI_CON_Ref

    Follower_AI_CON_C

    None

    TargetToFollow

    BlackboardKeySelector

    None - However, this variable has its "Editable" flag set to True so you can change it, per instance, on the Behavior Tree.

Here is what is going on in this graph:

  1. The Event Receive Execute is the event that is called when the Behavior Tree runs this task node.

  2. We store the Follower_AI_CON like we did in the previous step.

  3. The Cast to Actor node pulls the "TargetToFollow" object value from the Blackboard and casts it to an Actor so we can use it in the AI MoveTo node.

  4. On success, the task will run the Finish Execute node successfully.

13 - Make a Decorator

Decorators, also known as conditionals in other Behavior Tree systems, are attached to either a Composite or a Task node and define whether or not a branch in the tree, or a single node, can be executed.

This Decorator is going to stop execution of the Rapid Move To branch of the Behavior Tree once the AI's Pawn is close enough to its target. While this could be handled in the Rapid Move To Task or by just using a Move To Task, this decorator can take in any Actor and can block execution of any branch. This makes it reusable in a number of situations.

Steps

  1. Open the FollowerBT Behavior Tree by Double-clicking it in the Content Browser.

  2. Click New Decorator button.

    It will create in the same folder as the Behavior Tree.

  3. Rename it in the Content Browser to "CloseEnough".

  4. The editor should have already opened it for editing, but if not, Double-click it in the Content Browser.

  5. In the Functions section of the My Blueprint Tab, "Override" PerformConditionCheck.

  6. Create the following graph in that new function:

    Copy Example

    Click the image to expand it, or click here to open it in the window.

    The variable names, types, and values for this Blueprint:

    Variable Name

    Type

    Value

    AI_CON_Ref

    Follower_AI_CON_C

    None

    AcceptableDistance

    Float

    0.0 - However, this variable has its "Editable" flag set to True so you can change it, per instance, on the Behavior Tree.

    TargetToFollow

    BlackboardKeySelector

    None - However, this variable has its "Editable" flag set to True so you can change it, per instance, on the Behavior Tree.

    As this is a Function Graph, if you use the Code Snippet from the graph image above, you will only get the center portion of the graph, and the beginning and end nodes will not be connected. Just wire those connects as the image shows, and it will work just fine.

  7. Event Receive Condition Check is the event sent to this Blueprint when the Behavior Tree hits a node with this condition on it.

  8. Once again, store the AI Controller so we can reference it later easily.

  9. Get the Actor we want to follow (the Player Pawn).

  10. Get the distance between that Actor and the AI Pawn.

  11. If distance is greater than a configurable amount, then the condition returns True. If not, then it returns False and blocks execution of the portion of the Behavior tree it is on.

This will make it so the Behavior Tree is not constantly cycling to the RapidMoveTo and back out again. Basically, if he caught up to the player, then stop.

14 - Build the Behavior Tree

You should now have all the pieces needed to build this Behavior Tree:

Let's break down what's going on.

  • The AI will just stand around if it hasn't detected a Pawn that isn't an AI Character.

  • The AgroCheck Service is constantly looking for a suitable target.

  • Once it finds one, the left most branch is open, and the AI runs towards the targeted Pawn.

  • Once it gets in range of that Pawn the branch is prevented from executing, thusly returning it to the top of the graph

  • If the desired Pawn hides, then the right most branch will be able to run, which causes the AI to move to the last know location of the desired Pawn.

  • Once there, it waits, then returns home.

  • At any time, if a suitable target is found, the right most branch will be forced to stop executing, and the left most branch will be opened.

Let us step through the creation of this tree.

Basic Setup

You may have already done this back in part 8 of this guide, but just in case you did not save those changes, here are the steps for creating the basic structure of the Behavior Tree:

  1. If the Behavior Tree is not open for editing, Double-click it in the Content Browser to open it for editing.

  2. Switch to Behavior Tree Mode

  3. When you first edit a Behavior Tree, it will only have the Root Node:

  4. You can Right-click in the Graph Editor to create nodes

    1. Add a Composites -> Sequence Node.

    2. Add two (2) Composites -> Selector Nodes.

  5. Connect the Root Node to one of the Selector Nodes

  6. Connect the newly connected Sequence Node to the Selector Node and the other Sequence Node. Then arrange them like so:

    2nd Selector Node on the left, Sequence Node on the right.

Add the Service

  1. Using the Right-click context menu on the top selector node, add a Services -> Agro Check Node.

  2. Select the Agro Check box on the Selector Node, and using the Details panel, set the Target to Follow property to TargetToFollow, set Target Location to TargetLocation, adjust the Interval to 0.5 and the Random Deviation to 0.0

Add the Tasks

  1. Right-click in the Graph area to bring up the context menu, and add the 4 Tasks: 1 Rapid Move To Node, 1 Wait Node, and 2 Move To Nodes:

  2. Connect the lower Selector Node to the Rapid Move To Node.

  3. Connect the Sequence node to the Move To Nodes, and the Wait Node.

  4. Arrange the nodes like so:

    From left to right: Rapid Move To, Move To, Wait, Move To.

  5. Select the left-most Move To Node, and using the Details Panel, set the Blackboard Key property on the to TargetLocation

  6. Set the Blackboard Key property on the right-most Move To Node to HomeLocation

  7. Select the Wait Node, and using the Details panel, set its Wait Time property to 2.5

  8. Select the RapidMoveTo node, and using the Details panel, set its Target to Follow property to TargetToFollow.

Add the Decorators

  1. Right-click the lower Selector node and select Add Decorators.. -> Blackboard .

  2. Right-click the lower Selector node and select Add Decorators.. -> Close Enough.

  3. Set the Observer Aborts property on the Blackboard decorator to Both, Key Query to Is Set, and the Blackboard Key to TargetToFollow

  4. Set the Acceptable Distance property on the Close Enough decorator to 100.0, and Target to Follow property to TargetToFollow.

  5. Right-click the Sequence node and select Add Decorators.. -> Blackboard.

  6. Right-click the Sequence node and select Add Decorators.. -> Is At Location.

  7. Right-click the Sequence node and select Add Decorators.. -> Blackboard.

    After adding all those decorators, the full node block should look like this:

  8. On the first Blackboard decorator, set the Key Query to Is Not Set, and the Blackboard Key to TargetToFollow

  9. On the second Blackboard decorator, set the Key Query to Is Set, and the Blackboard Key to TargetLocation

  10. On the Is At Location decorator, enable the Inverse Condition property and set the Blackboard Key to HomeLocation.

    After setting those properties, the full node block should look like this:

And that is it! Leave the Behavior Tree editor open while using Play in Editor and you will be able to see how the tree is operating. If you get close enough to the AI and it has line of sight to you, it will begin to chase you. If you are able to break line of sight, he will go to your last known location, wait, then return to where he started.

15 - Next Steps

There's so much more you can do to this simple tree, why don't you give some of these ideas a try?

  • Using a Dot Product node, make it so the AI Character only chases the player when they are in front of the AI.

    • Bonus: Instead of using the AI Character's rotation as part of the Dot Product, use the rotation of the Head Joint.

    • Double Bonus: In the Animation Blueprint add functionality to control the rotation of the head joint, then create a service that has the AI look around.

  • Add attack functionality to the AI Characters and their Behavior Tree.

  • Instead of storing the last known location of the player, store the last 3-5 known locations, then when the player character can no longer be seen, calculate the most likely vector they may have gone, and move along it for a time.

  • They currently just stand their ground when not chasing the character, make it so they move around a bit near their Home Location.

  • Create a patrol point Actor, and make the AI move randomly between them.

    • Bonus: Have the patrol points store a linking patrol point so they will move in a pattern

    • Double Bonus: Have the patrol points store a number of acceptable linking points, then have the AI choose between them.

    • Super Bonus: Use Environment Query System to choose the best point for them to patrol.

  • Integrate the Environment Query System into the Behavior tree to choose places to stand or mull around.

  • Change the move speed of the AI Character to a walk when they are patrolling, but make them run when they are chasing the player.