Creating Modular Waypoint System in Unity
As for the player also to move the guards I will use the navmesh system. So to every guard, I have assigned a navmesh agent. Unlike the player, I have to create a system that doesn’t need external input. So I have to create a system that sequentially modifies the SetDestination method that offers us the “NavMeshAgent” class.
To do this, I need to create a system of points to use their position as a Vector3 to communicate to the SetDestination method.
We start by deciding what will be the movement pattern that one of our guards will have to follow. We decide where to put our empty GameObjects, these will be our waypoints.
Now we move on to the code, the goal is always the same, write reusable code. Even if they will have different movement patterns, all the guards must be able to use the same script. So the movement method must be the same with 1 waypoint or with 100 waypoints.
I define a container for our waypoints, I decided to use a list, of which we will define the size directly in our Inspector. We also declare the NavMeshAgent to be able to use its methods later. I recommend that when we want to use the NavMesh class we need to import the UnityEngine.AI library.
Finally, we define an integer variable that will be the pivot of the operation of our process.
The basic idea, when the guard reaches a waypoint, I increase my variable so that the waypoint will update to the next one and then he can go back.
So the first goal is to understand when I arrive at the first waypoint to update its destination. To do this we use a Vector3 method that allows us to calculate the distance between two positions and returns a float value.
We have to consider other aspects too, if there are no subsequent waypoints, how do I go back?
To solve this problem, let’s check if we are at the first or last point and reverse the flow. If before we increased our variable by one unit, now we will decrease it by one. In this way, we will create a ping pong effect.
When inserting animations, it is also necessary to take into account the transition between them and to manage the case of a single stationary waypoint and therefore of a guard that does not move and remains in Idle.
This led me to use a coroutine, in order to time the transition between the two states of animation, and manage the transaction between the waypoints