Tốc độ bắn
Bài học 11 trên 25 trong khóa học Game Unity: thủ thành của Coddy.
Mỗi tháp bắn một lần mỗi giây. Tháp Arrow nên bắn nhanh hơn, còn tháp Cannon xuất hiện sau nên bắn chậm hơn. Vì vậy, tốc độ bắn trở thành một trường (field): số phát bắn mỗi giây. Thời gian giữa hai phát bắn bằng 1 chia cho tốc độ bắn:
nextShot = Time.time + 1f / 4f; // 4 phát bắn mỗi giây: cách nhau 0.25 giâyMẫu tạo sẵn ArrowTower đặt tốc độ bắn thành 1.5: cứ 0.67 giây bắn một phát.
Thử thách
DễĐể mỗi tháp bắn với tốc độ riêng.
- Trong
Tower, thêmpublic float fireRate = 1.5f;(số phát bắn mỗi giây). - Sau mỗi phát bắn, đặt
nextShot = Time.time + 1f / fireRate;.
Nhấn Chơi: các mũi tên bắn ba phát mỗi hai giây. Sau đó nhấn Kiểm tra.
Tự làm thử
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);
}
}
Tất cả bài học trong Game Unity: thủ thành
Tự luyện tập: Playground Unity