My journey becoming a Unity game developer: Enemy AI-Setup the guards to patrol the area (Part 4)
Objective: Having the security guards pause at the 1st and last waypoints, and moving to the waypoints without any hesitation.
Let’s start by going into the GuardDelay() coroutine and checking IF the current target equals zero OR current target equals the end of the wayPoints List. If either of those conditions are met, we will pause between 2 to 5 seconds at that waypoint.
Looking at the guards moving on their patrol we notice the guards paused at the 1st waypoint, but didn’t pause at the last waypoint.
Next, we will use an Else statement to pause the script and continue with executing the code in the next frame.
While the script was allowed to pause and give the code a chance to execute, we still have the problem with the guards not pausing at the last waypoint.
If we look a little deeper, the problem seems to be that the wayPoints List Count adds up to 3 waypoints. However, the current target which is using the element index number to count adds up to 2 since the first number in the elements index is zero which represents the first number that is counted. Therefore, the current target and wayPoints Count doesn’t equal each other. To fix this we will deduct one from the wayPoints List Count to make this list equal 2 now instead of 3 which matches the current target element index number of 2 as well.
We see the guards now pausing at the 1st and last waypoints between 2 to 5 seconds on their patrols. Also, notice as the guards move into the waypoint, they will slow down from their regular speed just as they reach the center of the waypoint.
If you prefer to make the guards move through any waypoints without slowing down, select a guard from the Inspector and head over to their NavMeshAgent.
Begin with turning off the Auto Braking setting. This setting will make the agent or in this case the guards brake like a car stopping at the red light automatically as it nears its destination. Turning off Auto Braking will not be good enough to allow the guards to move through the waypoint without delay only.
Next, we need to set the Stopping Distance to something that might possibly land exactly at the target point which for us will be 1. This property can be used to set an acceptable radius within which each guard should stop. A larger stopping distance will give the guards more room to maneuver to the waypoint inside their paths, and might avoid sudden braking, turning or other odd AI behavior. Be careful with the values you use as they can stop the guards from moving when they reach near the waypoints.
If we look at this demonstration with the Auto Braking and Stopping Distance, keep your eye on the 1st guard and watch his behavior as we change his settings.
Next time we will begin adding animations for the Security Guards to use on their patrols.