Chasing a Player
Last updated
Last updated
This guide will create an agent behavior that chases a player. If there isn't a player in range the agent will instead wander around aimlessly.
Create a new tree and rename it "Wander".
Open the new tree and add a new "Sequence" node.
Connect the "Root" node to the "Sequence" node.
Create a "Wander" and connect it to the "Sequence" node. The radius parameter controls how far the agent will wander.
Create a new "Wait" node and connect it to the "Sequence" node as well. The duration parameter controls how long the agent should wait.
Open the scene "Wander" in "Examples/Tutorials". This scene has a baked navmesh and a simple GameObject with a NavMeshAgent component.
Add a BadgerAgent component to the GameObject and in the "Asset" field select the newly created "Wander" tree.
Press play! The agent will now wander around the scene.
Create a new tree and name it "Chase".
Create a new blackboard and add a new GameObject key called "Target".
Assign the new blackboard to the "Chase" tree. This enables us to add "Target" as a node condition.
Open the "Chase" tree and add a "MoveToObject" node. The threshold parameter determines how far the target GameObject has to move before we re-calculate a new path. In the GameObject field, we can now select the "Target" key we made previously. Add the "Target" key as a condition and set it to "NotNull". This node will only be explored if our agent has a "Target" in its blackboard.
Add a new "SubTree" node and assign the "Wander" tree we made before. BadgerHTN supports modular/reusable trees and you can view the search state of multiple trees simultaneously.
Connect both of the new nodes to the "Root" node. The "Root" node behaves in the same way as a "Selector" node and will first explore the "MoveToObject" node and then the "SubTree".
Our new agent needs something to target so let's add a player to the scene. Add a new Player GameObject and add a player controller to it. You can add any type of controller you want and there is a sample controller in the "Examples/Guides/02 Chase" scene.
Our new chase behavior requires that the agent has a target before starting the chase. We can make a simple script that updates the agent's blackboard with target information. Create a new MonoBehaviour script and open it. Here is an example script to update the agent's target when a GameObject gets close enough.
Attach the targeting script to the agent and assign the player GameObject to the "Target" field.
Pressing "Play" will now have the agent chasing after the player when it comes in range.