Modular Waypoint System- Game Dev Series 69
Objective: create a modular waypoint system to AI.
The first challenge of our stealth game is facing 3 guards with different patrol routes. Our player needs to sneak out from them first to get closer to goal.
In this article, we will create a modular system to our guards to find out the next waypoint.
We have to design the movement pattern first.
Here are 3 different routes of our guards.
The first yellow one, would make a simple route and head back if reached the end.
The second blue one, would move to an intersection waypoint, and randomly pick one from left or right as the next waypoint, then also go reverse till the starting position.
The last red one would only idling at its position with no movement waypoints.
Now we can start making the patrol route.
Simple patrol route
The idea of this article is creating a system. That means we will control all guards with only one script.
Create a script called Guard and attach it to guards. And also create a NavMeshAgent component to them.
In this script, let’s create a List variable to set the waypoints, and make it SerializeField to adjust in Inspector.
Back to Editor, we need to create the transform of waypoints to drag into the script.
To do this, we can duplicate the guard and drag it to the position we want.
Remove their children objects and components, just leave the transform. Rename them as waypoints.
Select the guard we will set first, and set the waypoint size to 3, then drag in the waypoints.
Back to script, create a NavMeshAgent and an integer variable. In the Update(), we will use the integer as moving destination.
This should make our guard moves on waypoints from the first one to the last.
However, it would cause error once it reaches the last waypoint. We need to make it heading back once it reaches the end.
To do so, we need another bool variable as a switch.
I use switch statement to identify the bool. When we reach the end on both sides, it will switch the bool.
And now our 1st guard should be able to walk on the route.
The random route
With the 2nd guard, we will make it pick up a random route every time. As what we did to the 1st guard, do the same setting to the 2nd guard, and add all the components that needed.
Since this guard has 4 waypoints, we can use this as a parameter in the switch statement.
And also make some changes of the bool-switching if statement.
Now our 2nd guard is ready!
For the last one. You don’t need to bother since it will be idle all the time. :)