Menu
CoddyTech

Aim

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

A tower turns to face its target: not the whole tower, which stands on its pad, but its head, a child object that carries the barrel. Turning a child turns everything under it and leaves the parent as it is.

The enemies walk lower than the heads, so the direction from a head to its enemy points a little down, and a head that looked straight along it would tip forward. Setting the direction's y to 0 keeps it level, so the head turns around the vertical axis only. A lighthouse lamp that follows a ship:

Vector3 toShip = ship.position - lamp.position;
toShip.y = 0f;
lamp.rotation = Quaternion.LookRotation(toShip);
Quaternion.LookRotation(direction) is the rotation that faces that direction, so the lamp snaps to the ship at once. A tower head should turn at a speed instead: Quaternion.RotateTowards(from, to, maxDegrees) from the Rotation chapter turns by at most maxDegrees, and a turn speed in degrees per second times Time.deltaTime gives each frame's share.
challenge icon

Challenge

Medium
  1. In Tower, add two serialized fields: head (a Transform) and turnSpeed (a float, degrees per second). The ArrowTower prefab gives its ArrowHead child and 270.
  2. While the tower has a target, turn the head toward it, around the vertical axis only, by at most turnSpeed degrees per second.
  3. With no target, leave the head as it is.

Press Play, build towers beside the path and watch them follow the enemies, then Check.

Try it yourself

using UnityEngine;

public class Tower : MonoBehaviour
{
    public int cost = 50;
    public float range = 4f;

    private Enemy target;

    void Update()
    {
        target = FindTarget();
    }

    Enemy FindTarget()
    {
        Enemy nearest = null;
        float nearestDistance = range;
        foreach (Enemy enemy in Enemy.All)
        {
            float distance = Vector3.Distance(transform.position, enemy.transform.position);
            if (distance <= nearestDistance)
            {
                nearest = enemy;
                nearestDistance = distance;
            }
        }
        return nearest;
    }
}
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