Menu
CoddyTech

発射速度

Coddyの「Unityゲーム:タワーディフェンス」コースのレッスン 11/25。

すべてのタワーは1秒に1回発射します。Arrowはもっと速く発射し、後から登場するCannonはもっと遅く発射する必要があるため、発射速度を「1秒あたりの発射数」というフィールドにします。2回の発射の間の時間は、1を発射速度で割った値です。

nextShot = Time.time + 1f / 4f; // 1秒間に4発:0.25秒間隔

ArrowTowerのプレハブでは発射速度が1.5に設定されており、0.67秒ごとに1発発射します。

challenge icon

チャレンジ

簡単

各タワーがそれぞれの発射速度で撃つようにしましょう。

  1. Towerに、public float fireRate = 1.5f;(1秒あたりの発射数)を追加します。
  2. 発射後、nextShot = Time.time + 1f / fireRate;を設定します。

「プレイ」を押します。「Arrows」は2秒ごとに3発撃ちます。その後、「確認」を押します。

自分で試してみよう

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プレイグラウンド