Menu
CoddyTech

射速

Coddy Unity 塔防游戏 课程的第 11 课,共 25 课。

每座塔每秒发射一次。箭塔应该发射得更快,而之后出现的加农炮发射得更慢,因此发射频率会成为一个字段:每秒发射次数。两次发射之间的时间是 1 除以发射频率:

nextShot = Time.time + 1f / 4f; // 每秒发射 4 次:每次间隔 0.25 秒

ArrowTower 预制体将发射频率设为 1.5:每 0.67 秒发射一次。

challenge icon

挑战

简单

让每座塔按自己的射速开火。

  1. 在 Tower 中,添加 public float fireRate = 1.5f;(每秒发射的子弹数)。
  2. 发射一枚子弹后,设置 nextShot = Time.time + 1f / fireRate;。

按下 Play:箭塔每两秒发射三枚子弹。然后点击 “检查”。

亲手试试

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

Unity 塔防游戏中的所有课

自己练习: Unity 在线编辑器