As you code more and more advanced AI you will need to create greater and greater types of complex movement. Simply following the player around isn’t enough to create compelling gameplay. For example when layered on other complex systems like the motion detection system we worked on previously or other behavior such as patrolling logic can make for interesting and varied gameplay. In this tutorial we’ll go ahead and create a modular way point system that you can use on the fly to tell the enemy where to patrol.
Let’s start by creating a new (or opening) project in Unity. For this tutorial we’ll use a simple plane and cube to illustrate this behavior. You can use this with your own models if yo wish but I find it easier to use primitives when blocking out new mechanics.
Next, we’ll make an empty gameobject named “Waypoints” to hold our cube’s waypoints. This will tell the cube where to go as it travels up and down the way points. Create 4 empty gameobjects called “Point” and number appropriately. Create a path that loops back on itself, I did a square using the empty gameobjects it may also be helpful to change the gizmo icon by hitting the top left of the inspector slot next to the gameobject name. I did red points to increase visibility.
Now with the points set up, it’s time to code in the Cube’s logic to follow the waypoints. Create a new script called Patrol and add it to the cube.
Now to get to the meat and potatoes,you can follow the code below.
Now let’s see it in action.
Now let’s add 4 more points to the waypoint parent object and make a more complex waypoint system to demonstrate the versatility.
Be sure to add them to the waypoint field on the Cube otherwise they may as well not exist. With that done, let’s see how it works.
There we have it, a fully operational modular waypoint system. This really only scratches the surface of what’s possible. However with this information you can layer on more complex functionality that will make your games truly shine. Until next time, happy coding.