발사 속도
Coddy의 Unity 게임: 타워 디펜스 코스 레슨. 25개 중 11번째.
모든 타워는 1초에 한 번 발사합니다. 화살 타워는 더 빠르게 발사해야 하고, 나중에 나오는 대포는 더 느리게 발사해야 하므로 발사 속도를 초당 발사 횟수로 설정합니다. 두 발사 사이의 시간은 1을 발사 속도로 나눈 값입니다.
nextShot = Time.time + 1f / 4f; // 초당 4발: 0.25초 간격ArrowTower 프리팹은 발사 속도를 1.5로 설정합니다. 즉, 0.67초마다 한 번 발사합니다.
챌린지
쉬움각 포탑이 자체 발사 속도로 발사하게 하세요.
Tower에public float fireRate = 1.5f;(초당 발사 수)를 추가하세요.- 발사한 후
nextShot = Time.time + 1f / fireRate;로 설정하세요.
‘플레이’를 누르세요. Arrows는 2초마다 세 발을 발사합니다. 그런 다음 ‘확인’을 누르세요.
직접 해보기
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);
}
}
Unity 게임: 타워 디펜스의 모든 레슨
직접 연습해 보세요: Unity 플레이그라운드