Cinematic Stealth Project — Modular Patrol Waypoints

Time to analyze the guard’s patrol pattern!

Pablo Gómez Platón
Nerd For Tech

--

It’s pretty common for videogame enemies to have a patrol pattern, moving from point to point, looking out to get the player. And obviously, a stealth game will always have pesky enemies patrolling around.

So, I’ve implemented modular patrol waypoints that will allow me to easily create new patrol paths and behaviour. Let me show you how that works:

Scene Setup

You’ll need a GameObject with the Nav Mesh Agent component, and various empty GameObjects that will act as your patrol waypoints. That’s really all you need to proceed.

This guard will be the test subject where I’ll implement the patrol behaviour

Code Setup

Create a new script, include the UnityEngine.AI library, and declare a new NavMeshAgent variable.

The patrol behaviour will need a reference to every waypoint that the guard will follow, and for that, I’ve created a List variable (using System.Collections.Generic) and an int variable to keep track of the currently selected waypoint. However, instead of holding a GameObject or Transform reference, the list will only accept GameObjects that have a specific script I’ve named PatrolPointInfo.

Let’s forget about this other script for now.

As soon as the game starts, the AI should start moving towards the first patrol point. We’ll also check if the patrol waypoints list is not empty and the first patrol point reference has been assigned in the Inspector.

The Patrol behaviour will constantly check if the agent has reached its destination by the distance between the agent and the destination’s position is lower or equal than a distance threshold.

For this example, the patrol path will not be cyclical and, instead, the AI will move back and forth after reaching the beginning or the end of the path.

And as a bonus, we should be able to see our waypoints. On the OnDrawGizmos method, we’ll scroll through each point and create a sphere for our waypoints, and lines between them.

And that’s it! We have a good modular patrol path that we can modify, even in runtime!

What about the PatrolPointInfo script?

There will be some patrol points that you’d wish to have more control over them. Maybe, you want the agent to stop at a certain point, or look towards a specific direction.

That’s where this script comes into play, helping you to increase the complexity of the Patrol behaviour while keeping it modular. I will add a bonus feature that will allow me to specify an idle time for each waypoint, and the agent will stay put during that time.

The script is very basic, and acts more like a data container. Add this script to your waypoints, and set a wait time in the Editor.

And for our main script, just checking for the wait time with a timer will be good enough to make this work with minimal effort.

Result

--

--