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
EasyMake the Grunt walk the path, waypoint to waypoint.
- In
Enemy, addprivate int next = 1;(the Grunt starts on WP0). - In
Update, return whennext >= waypoints.Length. - Move toward
waypoints[next].positionwithVector3.MoveTowardsatspeed * 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