Hi Everyone,
In they scrip down - I build turret which finds the Instantiated enemy objects, and then rotate to the closest turret in it range.
The script is work fine but I wonder about something wierd, I really sure that Im missing something Important.
when i set the var
shortestDistance = Mathf.Infinity;
inside Start() {
Instead of Update()
The turret find and rotate only to the first enemy, and then stop working,
Please help.
Thank you.
public class Turret : MonoBehaviour
{
public Transform target;
public float range = 20f;
public string enemyTag = "Enemy";
public Transform partToRotate;
public float distanceToEnemy;
public float shortestDistance;
// Start is called before the first frame update
void Start()
{
InvokeRepeating("UpdateTarget", 0f, 0.5f);
}
void UpdateTarget()
{
shortestDistance = Mathf.Infinity;
GameObject[] enemies = GameObject.FindGameObjectsWithTag(enemyTag);
GameObject nearestEnemy = null;
foreach (GameObject enemy in enemies)
{
distanceToEnemy = Vector3.Distance(transform.position, enemy.transform.position);
// Here the distance to enemy change every enemy is spawn.
if (distanceToEnemy < shortestDistance)
{
shortestDistance = distanceToEnemy;
nearestEnemy = enemy;
Debug.Log(shortestDistance);
}
}
if (nearestEnemy != null && shortestDistance <= range) // distance to enemy
{
target = nearestEnemy.transform; // here the turret action start.
}
else
{
target = null;
}
}
// Update is called once per frame
void Update()
{
if (target == null)
return;
Vector3 dir = target.position - transform.position;
Quaternion lookRotation = Quaternion.LookRotation(dir);
Vector3 rotation = lookRotation.eulerAngles;
partToRotate.rotation = Quaternion.Euler(0f, rotation.y, 0f);
}
void OnDrawGizmosSelected()
{
Gizmos.color = Color.red;
Gizmos.DrawWireSphere(transform.position, range);
}
}