Nerd For Tech
Published in

Nerd For Tech

Waypoint-Patrolling AI With Branching Paths In Unity, Part 2

For my stealth project, I had to make patrolling guards. However, I decided to mix it up with some randomly-selected alternate paths, and a “look direction”.

This post follows on from Part 1, so read that first if you haven’t.

The guard randomly chooses an alternate waypoint position to go to, when enabled.

Today’s Objective: Add alternate Waypoints to the existing waypoint-patrol system, to allow the guard to randomly choose between 2 points on certain Waypoints.

The code:

To add alternate points, we need to modify some of the existing code created in Part 1 of this post, as well as write some additional code.

Firstly, create this new struct underneath the existing Waypoint struct. Don’t overwrite the Waypoint struct.

Now modify the Waypoint List to be a List of WaypointContainers now.

Now in the existing “SetDestinationAndStartWalking( )” method, replace this existing code with this updated code:

This randomly chooses either the Primary or Alternate Waypoint as the destination.

Now I’ll modify the “Wait( )” method to add slowly rotating to face the waypoint’s LookDirection:

Drawing all the Scene View debug lines:

By this point, the “OnDrawGizmos( )” method has become pretty large (at 120 lines, a bit under half of the whole class), so I won’t show you how to draw all these nice debug lines again. If you followed Part 1, I’m sure you can figure it out yourself. It really makes it easier to work with the Waypoints though.

The result:

Although he does seem to like 1 path in particular in this test, each Primary/Alternate selection is a 50/50 chance.
Here you can see all the Waypoint “Primary”s, and their “Alternates” if enabled.

You may have noticed that along with the red lines and sphere from the LookDirection of each Waypoint, there are also either 2 or 3 redlines partially covering the lines between Waypoints.

These are from a change which I haven’t show here, which allows the AI agent to start turning towards the LookDirection before they actually reach the Waypoint. This makes it look more natural.



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Vincent Taylor

Vincent Taylor

Unity game developer / C# Programmer / Gamer. Australian (Tasmanian) indie games developer for 10+ years. Currently looking for games industry employment.