With your Waypoints set up, it is time to update your Enemy to follow your Waypoints.
You can utilize Unity's built in method Vector3.MoveTowards
to do most of the heavy lifting for the Enemy's movement.
Vector3.MoveTowards
to update the Enemy's position
maxDistanceDelta
While you are in Play Mode you can even switch the Waypoint to test that when the Waypoint is changed, the Enemy will move to the new Target
You need a way to determine how close the Enemy is to their Target Waypoint. This can be done using Vector3.Distance
.
distance
is sufficiently close to 0, the Enemy's Target updates to the next WaypointYou may have noticed the odd expressions distance <= 0
and might be asking yourself, "Why are we checking if the distance is less than or equal to 0 and not just equal to 0?". Great question! I'm so glad you asked! As you may already be aware, floating point numbers are approximated values, that is they should not be used for precise calculations (See: Is floating-point math broken? - Stack Overflowfor greater detail).
In our case, it is possible that we may not actually get a value of 0, and instead we want to check if the distance
is sufficiently close to 0. In Unity, this often done using Mathf.Epsilon
(which happens to be approximately 0.00001f).
Mathf.Epsilon
in place of 0You may have noticed, when your Enemy reaches the final Waypoint an error message appears in the Unity Console.
Currently, your Enemy begins its journey by moving to your first Waypoint. You may have already moved the Enemy to start at that position when you enter Play Mode. However, it is not guaranteed. One way to fix this, is to use the Start() method to move the Enemy to their first Target before the first game frame.
Start()
method to set the Enemy's initial position to the Target's position.If you placed your Waypoints such that their Y position is at 0 (level with your grid), you might have noticed that when your Enemy's model is slightly below the ground. You might be tempted to move your Waypoint's such that they are slightly above the ground. This would solve this issue. However, you can instead adjust your Enemy Prefab to such that the inner model is slightly elevated relative to the parent object.
Unity provides a method called Transform.LookAt
that can be used to make a Game Object rotate toward another Game Object. You can utilize this, to make your Enemy face their Target Waypoint.
When you have successfully completed this challenge, your Enemy should look similar to the one in the video below.
With your Enemy's moving, it is time to create an Enemy Spawner that will generate additional enemies during game play.