Velocità di fuoco
Lezione 11 di 25 del corso Gioco Unity: Tower Defense di Coddy.
Ogni torre spara una volta al secondo. Una torre con frecce dovrebbe sparare più velocemente e un Cannone, che arriverà più avanti, più lentamente, quindi la frequenza diventa un campo: colpi al secondo. Il tempo tra due colpi è 1 diviso per la frequenza:
nextShot = Time.time + 1f / 4f; // 4 colpi al secondo: a 0.25 secondi di distanza l’uno dall’altroIl prefab ArrowTower imposta la sua frequenza a 1.5: un colpo ogni 0.67 secondi.
Sfida
FacileFai in modo che ogni torre spari alla propria cadenza.
- In
Tower, aggiungipublic float fireRate = 1.5f;(colpi al secondo). - Dopo un colpo, imposta
nextShot = Time.time + 1f / fireRate;.
Premi «Gioca»: le frecce sparano tre colpi ogni due secondi. Poi premi «Verifica».
Provalo tu
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);
}
}
Tutte le lezioni di Gioco Unity: Tower Defense
Esercitati da solo: Playground Unity