Category Archives: Navigation

Navigation with the Nav Mesh Part 4: Patrolling and Chasing

 

Before you start
This tutorial won’t make any sense if you haven’t first done Part 1, Part 2, and Part 3.

And as with the rest of this series, you can grab a download of the full code as it should be at the end of this part of the tutorial at the bottom of this tutorial, so you can compare your own project.

Now that we’ve covered the basics of using the Nav Mesh, Nav Mesh Agent, and Nav Mesh Obstacle, let’s make better use of those tools to create something more game-like: an enemy.

We’ll create a simple enemy that uses the Nav Mesh for navigation, and has two types of behaviour – patrolling and chasing the player.

Create an Enemy

We’ll use our existing agent as our player, and create a new one to use as an enemy:

  1. Duplicate the Agent GameObject, and rename the copy ‘Enemy’ (Hint: Ctrl-D duplicates the selected object).
  2. Move the enemy far away from the player’s position.
  3. Change the enemy’s material and/or shape to make it distinct from the player (I changed mine to a cube and added a new orange material).
  4. Remove the Agent script (NOT the Nav Mesh Agent component) from the enemy (we’ll replace it with a different script).
  5. Rename the original Agent object to ‘Player’ for clarity.

To start with, we will make the enemy chase the player, as this is actually simple to implement. All we need to do is set the enemy’s Nav Mesh Agent destination to the player’s position, and update it periodically.

Enemy Script

We will build our enemy script in multiple stages, so you can either add in each piece of code as you read, or you can wait until the end of this section, where the whole script is listed.

  1. Create a new C# script and call it ‘Enemy’.
  2. Replace all the code in the script with the following:

using UnityEngine;
using UnityEngine.AI;
public class Enemy : MonoBehaviour {

NavMeshAgent agent;
[SerializeField] float decisionDelay = 3f;
[SerializeField] Transform objectToChase;

void Start () {
agent = GetComponent();
InvokeRepeating("SetDestination", 1.5f, decisionDelay);
}

void SetDestination() {
agent.SetDestination(objectToChase.position);
}
}

That code simply tells the enemy to move towards the object it is following, and repeats this via InvokeRepeating every 3 seconds (this is a long time between updating the destination, but it is much easier to see the behaviour in action with a long delay).

Now setup the enemy object:

  1. Drag the Player GameObject into the empty Object to Chase field in the Enemy’s Inspector window.
  2. Set the enemy’s Nav Mesh Agent Speed, Acceleration, and Angular speed settings slower than the play (or they will catch the player too easily!).

Test the scene. The enemy will wait 1.5 seconds and then start moving towards the player’s position. The enemy updates their destination (to the player’s current position) every 3 seconds. Try adjusting the Enemy’s Decision Delay and also their Nav Mesh Agent settings to get a good result. You don’t want them to easily reach the player, but you also don’t want them to be too slow.

At the moment the enemy constantly chases the player. This is OK for a simple demo, but let’s make it more interesting.

Catching the Player

Let’s implement a rudimentary way for the enemy to catch the player. This will make the project feel a bit more game-like. We will restart the scene when the player and enemy touch, so add this code to the enemy script (and make sure to save the script):

Firstly, add the following to the top of the Enemy script:


using UnityEngine.SceneManagement;

Then add the following method in the script body:


private void OnCollisionEnter(Collision collision)
{
if (collision.transform.name == "Player")
{
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
}
}

That code requires a Rigidbody component on the enemy in order to cause the collision, so in Unity, add a Rigidbody component to the Enemy GameObject.

BUG NOTE:

Unity has a bug that causes lighting to break when reloading a scene (this only affects the Unity editor – not actual game builds). If the scene goes dark when the enemy catches the player and restarts the scene, do the following to work around the bug:

  1. Go to the Unity menu and choose Window > Lighting > Settings.
  2. Select the Scene tab.
  3. At the bottom of the window, untick the Auto Generate button.
  4. Click the Generate Lighting button.

Test the scene, and now the enemy will chase and catch the player, causing the scene to restart. f you want, add some extra code to the collision so something more interesting happens when the enemy catches the player – try adding some sound or making a message display on the screen.

Patrolling

In many games, enemies patrol. Our enemy will patrol between a few waypoints, and will switch to chasing the player if the player gets close. If the player then moves far enough away from the enemy, the enemy will resume patrolling.

Waypoints

Let’s create a simple waypoint script to make the patrol waypoints visible in the Scene window, which will make it easier to place them and visualise the enemy’s movement. Create a new C# script called Waypoint, and replace all the code inside with the following:


using UnityEngine;

public class Waypoint : MonoBehaviour {

private void OnDrawGizmos()
{
Gizmos.color = Color.red;
Gizmos.DrawWireCube(transform.position, new Vector3(1.5f, 1.5f, 1.5f));
}
}

Any object with the Waypoint script will have a cube drawn at its position in the Scene window, which will be useful when setting up the enemy waypoints.

Now create all the waypoints in the scene:

  1. Create a new GameObject in the scene called Waypoint.
  2. Add the Waypoint script to the Waypoint GameObject.
  3. Create a prefab from the Waypoint GameObject by dragging the object into the Assets folder (create a Prefabs subfolder).
  4. Place the Waypoint GameObject near to the Enemy (this is the first waypoint).
  5. Create four more Waypoint objects by duplicating the existing one or by dragging the prefab into the scene.
  6. Rename the Waypoints sequentially (e.g. ‘Waypoint 1’, ‘Waypoint 2’, etc.) so you can easily place them in the right order.
  7. Place the waypoints so that they form a path for the enemy to travel along. In our code we will make the path a loop, so that the enemy returns to the first waypoint after reaching the last one.
  8. To ensure the waypoints are actually on the ground, set the Y position of all of them to 0.

Here are the waypoints in my project (the red cubes):

The enemy needs to know about the waypoints in order to move between them, so make the following changes to the Enemy script. Firstly, add a new array variable to hold all the waypoint positions:

[SerializeField] Transform[] waypoints;

Select the Enemy object in the Hierarchy and then go over to the Inspector window. In the Waypoints area, you need to enter the number of waypoints you have in the Size field, like this:

Now add references to the waypoints in the enemy script by dragging the waypoint objects from the Hierarchy into the empty fields in the Inspector, like so (do them in the correct order!):

State

The enemy needs to know when  to chase the player and when to patrol. For this simple example, we will use an enum variable to determine the enemy’s state, and determine behaviour based on its value.

First, we need to create an enum type and add it to the enemy script. Place the following code in the script. I usually put this sort of thing up with the variables:


enum EnemyStates {
Patrolling,
Chasing
}

Now, add the following variable to the script:

[SerializeField] EnemyStates currentState;

If you’ve not used enums before, you can think of them like a custom variable type that you specify the possible values for. In this case, a variable of type EnemyStates can only have one of two values: EnemyStates.Patrolling or EnemyStates.Chasing. The first value in the list is the default, meaning our enemy will start off in the Patrolling state until something changes that.

Patrolling Movement

Let’s get back to the patrolling movement. We’ll keep it simple. The enemy, when patrolling, will move to the next waypoint on their route, and when they reach the final waypoint, will return to the first one.

Add a new variable to keep track of which waypoint the enemy is currently walking toward:

int currentWaypoint = 0;

Add the following Update() method to the script:


void Update()
{
if(currentState == EnemyStates.Patrolling)
{
if(Vector3.Distance(transform.position, waypoints[currentWaypoint].position) < 0.6f)
{
currentWaypoint++;
if (currentWaypoint == waypoints.Length)
{
currentWaypoint = 0;
}
}
agent.SetDestination(waypoints[currentWaypoint].position);
}
}

That should be self-explanatory, but in a nutshell it updates the destination to the next waypoint when the agent gets close to the current target waypoint.

We also need to make a change to our chasing code, as the way it is done now would make the enemy try to patrol and chase at the same time! We need to make the chasing conditional upon the current state, so change the SetDestination() method to the following:


void SetDestination() {
if(currentState == EnemyStates.Chasing) agent.SetDestination(objectToChase.position);
}

Finally, add this as the last line of the Start() method to initiate the patrolling:

if(currentState == EnemyStates.Patrolling) agent.SetDestination(waypoints[currentWaypoint].position);

The enemy script would not win any awards for great code, but it’s good enough to demonstrate the simple behaviour we need.

Test the level to make sure the patrolling is working. If the enemy moves to the first waypoint and then stops, try changing the 0.6f value in the Update method to something higher. You can also change the enemy’s current state to chasing in the Inspector, and the enemy will stop patrolling and chase the player instead. Try changing it back and forth. Great, now there are two states, but the enemy needs a way to decide which state to be in.

Since we’re more interested in the navigation, we’ll cheat with the AI here. We will have a couple of simple rules to switch the enemy behaviour:

  • If the player is less than 10 units away from the enemy, the enemy will chase.
  • If the player is 10 or more units away from the enemy, the enemy will patrol.

We’ll pretend that the enemy can only hear or see the player when they are close.

Add this code to the Update() method before the code that is already in there:


if(Vector3.Distance(transform.position, objectToChase.position) >10f)
{
currentState = EnemyStates.Patrolling;
}
else
{
currentState = EnemyStates.Chasing;
}

On every Update(), the enemy will check how close the player is, then change state if necessary. You can now test the scene and make sure the enemy chases the player when the player gets too close. Try changing some of the values to make it feel right. The player needs to be faster than the enemy (so the player can run away), and the distance the enemy can detect the player needs to be enough to prevent the player escaping immediately. You may also want to adjust how long it takes the enemy to update their destination when chasing the player.

Tip: You can add a gizmo to the script to visualise how far away the enemy can detect the player. Add something like this:


private void OnDrawGizmos()
{
Gizmos.DrawWireSphere(transform.position, 5f);
}

The value of 5 here is the radius, which should be half the distance used in the code that checks the distance between the player and enemy. The gizmo will appear as a wire sphere around the enemy in the Scene view.

Done

That’s everything for Part 4. You should now have an enemy that switches between chasing the player and patrolling. The way this works and feels will depend a lot on the various values you use for everything, and there’s no better way to get it right than trial and error.

Download: Here is a download for the project as it should be as of the end of this tutorial: Part 4 download.

Here’s the full Enemy script including all the pieces from above:


using UnityEngine;
using UnityEngine.AI;
using UnityEngine.SceneManagement;

public class Enemy : MonoBehaviour {
NavMeshAgent agent;
[SerializeField] float decisionDelay = 3f;
[SerializeField] Transform objectToChase;
[SerializeField] Transform[] waypoints;
int currentWaypoint = 0;

enum EnemyStates
{
Patrolling,
Chasing
}

[SerializeField] EnemyStates currentState;

void Start () {
agent = GetComponent<NavMeshAgent>();
InvokeRepeating("SetDestination", 0.5f, decisionDelay);
if(currentState == EnemyStates.Patrolling) agent.SetDestination(waypoints[currentWaypoint].position);
}

void Update()
{
if(Vector3.Distance(transform.position, objectToChase.position) > 10f)
{
currentState = EnemyStates.Patrolling;
}
else
{
currentState = EnemyStates.Chasing;
}
if(currentState == EnemyStates.Patrolling)
{
if(Vector3.Distance(transform.position, waypoints[currentWaypoint].position) <= 0.6f)
{
currentWaypoint++;
if (currentWaypoint == waypoints.Length)
{
currentWaypoint = 0;
}
}
agent.SetDestination(waypoints[currentWaypoint].position);
}
}

void SetDestination() {
if(currentState == EnemyStates.Chasing) agent.SetDestination(objectToChase.position);
}

private void OnCollisionEnter(Collision collision)
{
if (collision.transform.name == "Player")
{
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
}
}

private void OnDrawGizmos()
{
Gizmos.DrawWireSphere(transform.position, 5f);
}
}

Navigation with the Nav Mesh Part 1: Setup and Basic Navigation

In this series of tutorials, we’ll go through setting up Unity’s built-in Nav Mesh, which enables pathfinding and navigation without the need for complex code.

Before you Begin

For Intermediate Unity Developers

This tutorial series is for intermediate Unity users. I won’t go into detail on Unity basics, and assume you know your way around Unity’s interface and core features. Please refer to the Pong tutorial for beginners if you are not yet familiar enough with Unity to follow this tutorial.

Unity Version

This project was created with Unity version 2017.3.1f1, which is the latest version at the time of writing. You should be OK with any Unity version that is not too much older or newer.

Download

A download link is at the bottom of this tutorial. It contains a project as it should be if all the instructions in this part of the tutorial are followed.

Navigation Basics

Unity comes with a great navigation system that can be set up quickly and easily, and gives your characters the ability to navigate a complex environment by pathfinding and avoiding obstacles.

Nav Mesh

Unity’s navigation solution is the Nav Mesh. The Nav Mesh is a map of the areas in your game where a character can walk. When you tell your character to walk to a position on the Nav Mesh, they will automatically find a path to that position (if possible) and move there. If the character can’t reach the target position, they will get as close as possible.

Nav Agent

For a character to use a Nav Mesh, they must have a Nav Mesh Agent component on their GameObject. This agent contains the capabilities needed for navigation on the Nav Mesh, and you call methods on this object to make the character move, and use the various settings to specify the precise behaviour you want.

Create a Basic Navigating Character

To start with, we will create a simple scene with a navigating character who moves from their starting position to a target position.

The Scene

If you want to skip the basic non-AI related stuff, download the starter project, which includes a pre-built scene with the basics already done for you so you can get straight into the good stuff.

The base project contains a single scene ‘MainScene’, with some ground, an Agent (who we will set up to navigate the world), and a target GameObject which we will use as the place the player will navigate towards.

Create the Base Project and Scene

If you would rather set up the base project yourself, here are the steps required (skip this part if you downloaded the base project, and simply open that project then continue to Add a Nav Mesh).

  1. Start a new 3D Unity project.
  2. Create a scene called ‘MainScene’.
  3. Add a large Plane object to act as the ground
  4. Add a small sphere or cube called ‘Agent’, and make sure it is above the ground. Place the Agent near one of the corners.
  5. Create another GameObject called ‘Target’, and give it any 3D shape, such as a cylinder or a cube, and place it far from the Agent object (we will be making the Agent navigate towards the Target).
  6. Add materials to the objects to separate the objects visually, and to make your scene more interesting.
  7. Setup the camera so that you can see the whole of the floor and have a good view of the Agent and Target objects.

Here is what my base scene looks like:

image

Add a Nav Mesh

A Nav Mesh is used differently to the typical Unity components. Instead of adding it to objects, you add objects to it. For this reason, there is a Navigation window that you must use to setup your Nav Mesh.

If you don’t already have the Navigation window visible, go to the Unity menu and select Window > Navigation:

image

This window has four tabs that present different options and customisations; these are:

  • Agents – customise the behaviour of AI characters (agents) using the mesh.
  • Areas – customise the different types of terrain (e.g. terrain that is slower to walk on or terrain that can’t be walked on).
  • Bake – this is where you apply all your settings and create the Nav Mesh.
  • Object – where you select which objects are included in your mesh, and some of their properties.

You will also see that there is a Scene Filter option. This allows you to hide objects in the scene Hierarchy while working on navigation. For example, if you choose the Mesh Renderers option, everything without a Mesh Renderer will be hidden in the Hierarchy, making it easier to find the objects you want to use for navigation. This will come in handy for complex scenes with lots of objects, but for this tutorial we don’t need to worry ourselves about this.

We won’t go into a lot of detail right now. For now, let’s just get something working.

In the Navigation window:

  1. Select the Object tab.
  2. Select the ground object in the Hierarchy to make it the active object.
  3. Check that the ground object is now selected in the Navigation window.
  4. Set the settings as below:
    1. Tick Navigation Static.
    2. Select Walkable in the Navigation Area drop-down box.
    3. Ignore Generate OffMesh Links for now (we’ll look at it later).

clip_image001

You’ve now told the Nav Mesh that you want the ground to be walkable, and that it is ‘navigation static’ (i.e. the Nav Mesh will ‘see’ it when determining the walkable areas). This is the most basic Nav Mesh setup you need.

Bake It

Although we’ve added the ground to the Nav Mesh and made it walkable and navigation static, we have not actually created the Nav Mesh. We need to ‘bake’ it. Baking is a process of doing something that is too complex or time-consuming to do at runtime during the development process. There is no need to create a navigation mesh during runtime, since the terrain doesn’t change much in a game (and small changes don’t require a complete rebuilding of the mesh). The same is done for complex lighting in many games.

  1. Select the Bake tab in the Navigation window.
  2. Click the Bake button.
  3. If you do not already have the Scene window open, open it to see your Nav Mesh.

In the Scene window, the Nav Mesh is presented as a blue overlay on the ground, which represents where Nav Mesh Agents are able to walk:

clip_image002

In our current project, it will just be a simple blue square, but this will change as we later add some complexity.

Add an Agent

A Nav Mesh is pointless without someone to walk around it. We will now turn the Agent object into a ‘Nav Mesh Agent’ who can navigate the Nav Mesh.

  1. Select the Agent object in the Hierarchy to make it the active object.
  2. Add a Nav Mesh Agent component to the object in the Inspector window.
  3. Set the Speed property to any number (between 5 and 10 would be ideal).

You’ll notice a lot of settings on the Nav Mesh Agent component. Some of these are quite obvious (e.g. Speed), and some are not quite so obvious. For now we’ll ignore these settings.

image

Script

We need some code to make the player navigate, but it’s probably not as much code as you think. The Nav Mesh Agent takes care of movement and navigation, and we only need to tell the agent where to walk to.

To keep things simple for now, we’ll set a static target for the player to move towards (the Target GameObject in our scene).

Now, create a new C# script called ‘Agent’. I won’t go into detail about the code, as most of it doesn’t directly have anything to do with navigation (and it’s pretty basic Unity code). The only line of code that is navigation specific is:

agent.SetDestination(target.position);

That line tells the agent where it should try to navigate to, and will trigger the agent to start moving if they are not already at the target.

Here is the full code for the Agent script:

using UnityEngine;
using UnityEngine.AI;
public class Agent : MonoBehaviour {
[SerializeField] Transform target;
NavMeshAgent agent;

void Start()
{
    // get a reference to the player's Nav Mesh Agent component
    agent = GetComponent<NavMeshAgent>();
    // set the agent's destination
    agent.SetDestination(target.position);
    }
}
  1. Save the script.
  2. Attach the script to the Agent GameObject.
  3. Drag the Target GameObject into the Agent’s Target field in the Inspector:

clip_image003

Yes, that’s all you need for now to get the player navigating towards the target!

Run the Scene

Run the scene and watch the player automatically move towards the target. You can try experimenting with some of the player’s settings, though some of them won’t have any effect on such a basic scene, as the navigation is going to always be in a straight line.

It’s perhaps not too impressive to see the character move in a straight line from start to finish, so in the next part, we’ll add some obstacles and see the pathfinding in action.

Download

Here is the download for the project as it should be at the end of this part of the tutorial. Download it if you get stuck or want to compare your project to mine.