Unreal Engine 4 Tutorial: Artificial Intelligence
In this Unreal Engine 4 tutorial, you will learn how to use behavior trees and AI Perception to create a simple AI character that roams and attacks enemies. By Tommy Tran.
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress, bookmark, personalise your learner profile and more!
Create accountAlready a member of Kodeco? Sign in
Contents
Unreal Engine 4 Tutorial: Artificial Intelligence
25 mins
- Getting Started
- What is a Controller?
- Creating an AI Controller
- Creating a Behavior Tree
- The Behavior Tree Editor
- What are Tasks and Composites?
- Moving to a Random Location
- Creating a Blackboard
- The Blackboard Editor
- Creating the Target Location Key
- What is a Service?
- Creating a Service
- Generating a Random Location
- Selecting a Blackboard
- Running the Behavior Tree
- Setting Up AI Perception
- Creating an Enemy Key
- Moving Towards An Enemy
- Setting the Enemy Key
- Creating an Attack Task
- Adding Attack to the Behavior Tree
- Combining the Subtrees
- Creating a Decorator
- Using Observer Aborts
- Where to Go From Here?
Setting Up AI Perception
AI Perception is a component you can add to actors. Using it, you can give senses (such as sight and hearing) to your AI.
Open AIC_Muffin and then add an AIPerception component.
Next, you need to add a sense. Since you want to detect when another muffin moves into view, you need to add a sight sense.
Select AIPerception and then go to the Details panel. Under AI Perception, add a new element to Senses Config.
Set element 0 to AI Sight config and then expand it.
There are three main settings for sight:
- Sight Radius: The maximum distance the muffin can see. Leave this at 3000.
- Lose Sight Radius: If the muffin has seen an enemy, this is how far the enemy must move away before the muffin loses sight of it. Leave this at 3500.
- Peripheral Vision Half Angle Degrees: How wide the muffin’s vision is. Set this to 45. This will give the muffin a 90 degree range of vision.
By default, AI Perception only detects enemies (actors assigned to a different team). However, actors do not have a team by default. When an actor doesn’t have a team, AI Perception considers it neutral.
As of writing, there isn’t a method to assign teams using Blueprints. Instead, you can just tell AI Perpcetion to detect neutral actors. To do this, expand Detection by Affiliation and enable Detect Neutrals.
Click Compile and then go back to the main editor. Press Play and spawn some muffins. Press the ‘ key to display the AI debug screen. Press 4 on the numpad to visualize AI Perception. When a muffin moves into view, a green sphere will appear.
Next, you will move the muffin towards an enemy. To do this, the behavior tree needs to know about the enemy. You can do this by storing a reference to the enemy in the blackboard.
Creating an Enemy Key
Open BB_Muffin and then add a key of type Object. Rename it to Enemy.
Right now, you will not be able to use Enemy in a MoveTo. This is because the key is an Object but MoveTo only accepts keys of type Vector or Actor.
To fix this, select Enemy and then expand Key Type. Set Base Class to Actor. This will allow the behavior tree to recognize Enemy as an Actor.
Close BB_Muffin. Now, you need to create a behavior to move towards an enemy.
Moving Towards An Enemy
Open BT_Muffin and then disconnect Sequence and Root. You can do this by alt-clicking the wire connecting them. Move the roam subtree aside for now.
Next, create the highlighted nodes and set their Blackboard Key to Enemy:
This will move the Pawn towards Enemy. In some cases, the Pawn will not completely face towards its target so you also use Rotate to face BB entry.
Now, you need to set Enemy when AI Perception detects another muffin.
Setting the Enemy Key
Open AIC_Muffin and then select the AIPerception component. Add an On Perception Updated event.
This event will execute whenever a sense updates. In this case, whenever the AI sees or loses sight of something. This event also provides a list of actors it currently senses.
Add the highlighted nodes. Make sure you set Make Literal Name to Enemy.
This will check if the AI already has an enemy. If it doesn’t, you need to give it one. To do this, add the highlighted nodes:
Summary:
- IsValid will check if the Enemy key is set
- If it is not set, loop over all the currently perceived actors
- Cast To BP_Muffin will check if the actor is a muffin
- If it is a muffin, check if it is dead
- If IsDead returns false, set the muffin as the new Enemy and then break the loop
Click Compile and then close AIC_Muffin. Press Play and then spawn two muffins so that one is in front of the other. The muffin behind will automatically walk towards the other muffin.
Next, you will create a custom task to make the muffin perform an attack.
Creating an Attack Task
You can create a task within the Content Browser instead of the behavior tree editor. Create a new Blueprint Class and select BTTask_BlueprintBase as the parent.
Name it BTTask_Attack and then open it. Add an Event Receive Execute AI node. This node will execute when the behavior tree executes BTTask_Attack.
First, you need to make the muffin attack. BP_Muffin contains an IsAttacking variable. When set, the muffin will perform an attack. To do this, add the highlighted nodes:
If you use the task in its current state, execution will become stuck on it. This is because the behavior tree doesn’t know if the task has finished. To fix this, add a Finish Execute to the end of the chain.
Next, enable Success. Since you are using a Sequence, this will allow nodes after BTTask_Attack to execute.
This is what your graph should look like:
Summary:
- Event Receive Execute AI will execute when the behavior tree runs BTTask_Attack
- Cast To BP_Muffin will check if Controlled Pawn is of type BP_Muffin
- If it is, its IsAttacking variable is set
- Finish Execute will let the behavior tree know the task has finished successfully
Click Compile and then close BTTask_Attack.
Now, you need to add BTTask_Attack to the behavior tree.
Adding Attack to the Behavior Tree
Open BT_Muffin. Afterwards, add a BTTask_Attack to the end of the Sequence
Next, add a Wait to the end of the Sequence. Set its Wait Time to 2. This will make sure the muffin doesn’t constantly attack.
Go back to the main editor and press Play. Spawn two muffins like last time. The muffin will move and rotate towards the enemy. Afterwards, it will attack and wait two seconds. It will then perform the entire sequence again if it sees another enemy.
In the final section, you will combine the attack and roam subtrees together.
Combining the Subtrees
To combine the subtrees, you can use a Selector composite. Like Sequences, they also execute from left to right. However, a Selector will stop when a child succceeds rather than fail. By using this behavior, you can make sure the behavior tree only executes one subtree.
Open BT_Muffin and then create a Selector after the Root node. Afterwards, connect the subtrees like so:
This set up will allow only one subtree to run at a time. Here is how each subtree will run:
- Attack: Selector will run the attack subtree first. If all tasks succeed, the Sequence will also succeed. The Selector will detect this and then stop executing. This will prevent the roam subtree from running.
- Roam: The selector will attempt to run the attack subtree first. If Enemy is not set, MoveTo will fail. This will cause Sequence to fail as well. Since the attack subtree failed, Selector will execute its next child which is the roam subtree.
Go back to the main editor, press Play. Spawn some muffins to test it out.
"Hang on, why doesn’t the muffin attack the other one immediately?"
In traditional behavior trees, execution starts from the root every update. This means every update, it would try the attack subtree first and then the roam subtree. This means the behavior tree can instantly change subtrees if the value of Enemy changes.
However, Unreal’s behavior trees do not work the same way. In Unreal, execution picks up from the last executed node. Since AI Perception does not sense other actors immediately, the roam subtree begins running. The behavior tree now has to wait for the roam subtree to finish before it can re-evaluate the attack subtree.
To fix this, you can use the final type of node: decorators.