Taxa de Disparo
Lição 11 de 25 do curso Jogo de Unity: Defesa de Torres da Coddy.
Cada torre dispara uma vez por segundo. Uma torre de flechas deve disparar mais rápido e um Canhão, que vem depois, mais devagar, então a taxa passa a ser um campo: disparos por segundo. O tempo entre dois disparos é 1 dividido pela taxa:
nextShot = Time.time + 1f / 4f; // 4 disparos por segundo: separados por 0.25 segundosO prefab ArrowTower define sua taxa como 1.5: um disparo a cada 0.67 segundos.
Desafio
FácilFaça cada torre disparar na sua própria cadência.
- Em
Tower, adicionepublic float fireRate = 1.5f;(disparos por segundo). - Após um disparo, defina
nextShot = Time.time + 1f / fireRate;.
Pressione “Jogar”: as setas disparam três vezes a cada dois segundos. Em seguida, pressione “Verificar”.
Experimente você mesmo
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 as lições de Jogo de Unity: Defesa de Torres
Pratique por conta própria: Playground de Unity