Menu
CoddyTech

Fire Rate

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

Every tower fires once a second. An Arrow should fire faster and a Cannon, which comes later, slower, so the rate becomes a field: shots per second. The time between two shots is 1 divided by the rate:

nextShot = Time.time + 1f / 4f; // 4 shots a second: 0.25 seconds apart

The ArrowTower prefab sets its rate to 1.5: a shot every 0.67 seconds.

challenge icon

Challenge

Easy

Let each tower fire at its own rate.

  1. In Tower, add public float fireRate = 1.5f; (shots per second).
  2. After a shot, set nextShot = Time.time + 1f / fireRate;.

Press Play: the Arrows fire three shots every two seconds. Then Check.

Try it yourself

using UnityEngine;

public class Tower : MonoBehaviour
{
    public float range = 4f;
    public int damage = 2;
    [SerializeField] private Transform head;
    [SerializeField] private float turnSpeed = 270f;
    [SerializeField] private Projectile projectilePrefab;

    private Enemy target;
    private float nextShot;

    void Update()
    {
        Enemy found = FindTarget();
        if (found != null && found != target)
        {
            Debug.Log("Target: " + found.name);
        }
        target = found;
        if (target == null)
        {
            return;
        }

        Aim();
        if (Time.time >= nextShot)
        {
            Fire();
            nextShot = Time.time + 1f;
        }
    }

    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;
    }

    void Aim()
    {
        Vector3 direction = target.transform.position - head.position;
        direction.y = 0f;
        Quaternion look = Quaternion.LookRotation(direction);
        head.rotation = Quaternion.RotateTowards(head.rotation, look, turnSpeed * Time.deltaTime);
    }

    void Fire()
    {
        Projectile shot = Instantiate(projectilePrefab, head.position + head.forward * 0.6f, Quaternion.identity);
        shot.Launch(target.transform, damage);
    }
}

All lessons in Unity Game: Tower Defense

Practice on your own: Unity playground