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.
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:
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:
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.