Menu
CoddyTech

Waypoints

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

In this course you build a tower defense game: enemies walk a path in waves toward your base, and towers you build beside the path stop them. Each lesson adds one feature. Press Play to try it and Check to grade it. All twelve scripts are in the project from the start; most are short stubs that later lessons fill in, and EnemyData is given for lesson 2.

The path is eight waypoints, WP0 at the spawn to WP7 at the base, in the Grunt's waypoints array. The Grunt keeps the index of the one it heads for and moves toward it. Vector3.MoveTowards never steps past its target, so the Grunt lands exactly on the waypoint and == can tell it arrived:

Vector3 target = waypoints[3].position;
transform.position = Vector3.MoveTowards(transform.position, target, 5f * Time.deltaTime);
if (transform.position == target)
{
    // arrived: head for the next one
}

After the last waypoint the index equals waypoints.Length, and reading the array there throws an error, so check the index before you use it.

challenge icon

Challenge

Easy

Make the Grunt walk the path, waypoint to waypoint.

  1. In Enemy, add private int next = 1; (the Grunt starts on WP0).
  2. In Update, return when next >= waypoints.Length.
  3. Move toward waypoints[next].position with Vector3.MoveTowards at speed * Time.deltaTime; when it gets there, next++.

Press Play: the Grunt walks every corner and stops at the base. 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.
    }
}

All lessons in Unity Game: Tower Defense

Practice on your own: Unity playground