Cadencia de disparo
Lección 11 de 25 del curso Juego de Unity: Defensa de torres de Coddy.
Cada torre dispara una vez por segundo. Una Arrow debería disparar más rápido y un Cannon, que aparece más adelante, más despacio, así que la frecuencia pasa a ser un campo: disparos por segundo. El tiempo entre dos disparos es 1 dividido por la frecuencia:
nextShot = Time.time + 1f / 4f; // 4 disparos por segundo: separados por 0.25 segundosEl prefab ArrowTower establece su frecuencia en 1.5: un disparo cada 0.67 segundos.
Desafío
FácilHaz que cada torre dispare a su propio ritmo.
- En
Tower, añadepublic float fireRate = 1.5f;(disparos por segundo). - Después de un disparo, establece
nextShot = Time.time + 1f / fireRate;.
Pulsa «Jugar»: las Arrows disparan tres veces cada dos segundos. Después, pulsa «Comprobar».
Pruébalo tú mismo
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);
}
}
Todas las lecciones de Juego de Unity: Defensa de torres
2Torres
Construir plataformasPractica por tu cuenta: Playground de Unity