76 lines
2.1 KiB
C#
76 lines
2.1 KiB
C#
using UnityEngine;
|
|
using System.Collections.Generic;
|
|
|
|
public class TowerAttack : MonoBehaviour
|
|
{
|
|
[Header("Tower Settings")]
|
|
public float range = 10f; // 사거리
|
|
public float fireRate = 1f; // 초당 발사 횟수
|
|
public GameObject projectilePrefab; // 화살/마법탄 등 프리팹
|
|
public Transform firePoint; // 투사체가 발사될 위치
|
|
|
|
private float _fireCountdown = 0f;
|
|
private Transform _target;
|
|
|
|
void Update()
|
|
{
|
|
UpdateTarget(); // 가장 가까운 적 찾기
|
|
|
|
if (_target == null) return;
|
|
|
|
// 발사 간격 관리
|
|
if (_fireCountdown <= 0f)
|
|
{
|
|
Shoot();
|
|
_fireCountdown = 1f / fireRate;
|
|
}
|
|
|
|
_fireCountdown -= Time.deltaTime;
|
|
}
|
|
|
|
void UpdateTarget()
|
|
{
|
|
// "Enemy" 태그를 가진 모든 오브젝트 검색
|
|
GameObject[] enemies = GameObject.FindGameObjectsWithTag("Enemy");
|
|
float shortestDistance = Mathf.Infinity;
|
|
GameObject nearestEnemy = null;
|
|
|
|
foreach (GameObject enemy in enemies)
|
|
{
|
|
float distanceToEnemy = Vector3.Distance(transform.position, enemy.transform.position);
|
|
if (distanceToEnemy < shortestDistance)
|
|
{
|
|
shortestDistance = distanceToEnemy;
|
|
nearestEnemy = enemy;
|
|
}
|
|
}
|
|
|
|
// 가장 가까운 적이 사거리 안에 있을 때만 타겟으로 설정
|
|
if (nearestEnemy != null && shortestDistance <= range)
|
|
{
|
|
_target = nearestEnemy.transform;
|
|
}
|
|
else
|
|
{
|
|
_target = null;
|
|
}
|
|
}
|
|
|
|
void Shoot()
|
|
{
|
|
GameObject projectileGo = Instantiate(projectilePrefab, firePoint.position, firePoint.rotation);
|
|
Projectile projectile = projectileGo.GetComponent<Projectile>();
|
|
|
|
if (projectile != null)
|
|
{
|
|
projectile.Seek(_target); // 투사체에게 타겟 정보 전달
|
|
}
|
|
}
|
|
|
|
// 에디터 씬 뷰에서 사거리를 시각적으로 확인
|
|
void OnDrawGizmosSelected()
|
|
{
|
|
Gizmos.color = Color.red;
|
|
Gizmos.DrawWireSphere(transform.position, range);
|
|
}
|
|
} |