Menu
CoddyTech

Szybkostrzelność

Lekcja 11 z 25 w kursie Gra w Unity: Obrona wieży w Coddy.

Każda wieża strzela raz na sekundę. Wieża Arrow powinna strzelać szybciej, a armata, która pojawi się później, wolniej, więc szybkość staje się polem: strzały na sekundę. Czas między dwoma strzałami to 1 podzielone przez szybkość:

nextShot = Time.time + 1f / 4f; // 4 strzały na sekundę: w odstępach co 0.25 sekundy

Prefabrykowana wieża ArrowTower ma ustawioną szybkość 1.5: strzał co 0.67 sekundy.

challenge icon

Wyzwanie

Łatwy

Niech każda wieża strzela we własnym tempie.

  1. W Tower dodaj public float fireRate = 1.5f; (strzały na sekundę).
  2. Po strzale ustaw nextShot = Time.time + 1f / fireRate;.

Naciśnij „Graj”: wieże strzelają trzy razy co dwie sekundy. Następnie naciśnij „Sprawdź”.

Spróbuj swoich sił

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

Wszystkie lekcje w sekcji Gra w Unity: Obrona wieży

Poćwicz samodzielnie: Edytor online Unity