Menu
CoddyTech

Waypoints

Lesson 1 of 18 in Coddy's Unity Game: Tower Defense course.

In this course you build a tower defense game. Enemies march along a path in waves toward your base, and you stop them with towers that you place on build pads, then upgrade and sell. Each lesson adds one feature. All twelve scripts of the game are in the project from the start; most are short stubs that later lessons fill in.

An enemy follows the path through waypoints: empty GameObjects at the corners, in an array in the order they are walked. The enemy keeps the index of the waypoint it heads for, moves toward it, and on arrival moves on to the next one. Vector3.MoveTowards(current, target, maxStep) moves a point toward a target by at most maxStep and never past it, so the enemy lands exactly on the waypoint and == can tell that it arrived. This patrol drone flies between its posts and starts over after the last one:

public Transform[] posts;
public float speed = 3f;
private int current;

void Update()
{
    Vector3 goal = posts[current].position;
    transform.position = Vector3.MoveTowards(transform.position, goal, speed * Time.deltaTime);
    if (transform.position == goal)
    {
        current = (current + 1) % posts.Length;
    }
}

An enemy does not loop: after the last waypoint there is nowhere left to go. Once the index reaches Length it no longer points at a waypoint, and reading waypoints[waypoints.Length] throws an IndexOutOfRangeException, so the index is checked before it is used. The waypoints sit 0.6 above the ground, the height of an enemy's centre, so walking straight at them keeps its feet on the ground.

challenge icon

Challenge

Easy

The Grunt stands on the first waypoint, WP0, and its Enemy script already has the eight waypoints in waypoints, from WP0 at the spawn to WP7 at the base.

  1. Add a private int next: the index of the waypoint the Grunt heads for. It starts on WP0, so next starts at 1.
  2. In Update, move the Grunt toward waypoints[next] at speed units per second with Vector3.MoveTowards.
  3. When it arrives on that waypoint, head for the next one.
  4. After the last waypoint, stop: no more moving and no errors.

Press Play and watch the Grunt walk the path, then Check.

Try it yourself

using UnityEngine;

public class Enemy : MonoBehaviour
{
    public float speed = 2f;
    public Transform[] waypoints;

    void Update()
    {
        // Walk the path here: from waypoint to waypoint, in order.
    }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Unity Game: Tower Defense