71 lines
2.3 KiB
C#
71 lines
2.3 KiB
C#
using Unity.Mathematics;
|
|
using Unity.VisualScripting;
|
|
using UnityEngine;
|
|
using UnityEngine.Rendering;
|
|
|
|
public class ProjectileTower : MonoBehaviour
|
|
{
|
|
private Tower theTower;
|
|
[SerializeField] GameObject projectile;
|
|
[SerializeField] Transform firePoint;
|
|
[SerializeField] float minTimeBetweenShot = 2f;
|
|
[SerializeField] float maxTimeBetweenShot = 6f;
|
|
private Transform target;
|
|
[SerializeField] private Transform launcherModel;
|
|
[SerializeField] private GameObject shotEffect;
|
|
private float shotCounter;
|
|
|
|
void Awake()
|
|
{
|
|
theTower = GetComponentInParent<Tower>();
|
|
}
|
|
|
|
void Start()
|
|
{
|
|
shotCounter = UnityEngine.Random.Range(minTimeBetweenShot, maxTimeBetweenShot);
|
|
}
|
|
|
|
void Update()
|
|
{
|
|
shotCounter -= Time.deltaTime;
|
|
if (shotCounter <= 0f && target != null)
|
|
{
|
|
Vector3 directionToTarget = (target.position - firePoint.position).normalized;
|
|
Quaternion aimRotation = Quaternion.LookRotation(directionToTarget);
|
|
Instantiate(projectile, firePoint.position, aimRotation);
|
|
shotCounter = UnityEngine.Random.Range(minTimeBetweenShot, maxTimeBetweenShot);
|
|
}
|
|
if (theTower.enemiesUpdated)
|
|
{
|
|
if (theTower.enemiesInRange.Count > 0)
|
|
{
|
|
float minDistance = theTower.range * 1f;
|
|
foreach (EnemyController enemy in theTower.enemiesInRange)
|
|
{
|
|
if (enemy != null)
|
|
{
|
|
float distance = Vector3.Distance(enemy.transform.position, transform.position);
|
|
if (distance < minDistance)
|
|
{
|
|
minDistance = distance;
|
|
target = enemy.transform;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
else
|
|
{
|
|
target = null;
|
|
}
|
|
}
|
|
}
|
|
void LateUpdate()
|
|
{
|
|
if (target != null)
|
|
{
|
|
launcherModel.rotation = Quaternion.Slerp(launcherModel.rotation, Quaternion.LookRotation(target.position - transform.position), 5f * Time.deltaTime);
|
|
launcherModel.rotation = Quaternion.Euler(0f, launcherModel.rotation.eulerAngles.y, 0f);
|
|
}
|
|
}
|
|
}
|