So, im making a TD game, and im trying to make the turret shoot at the closest enemy in a sphere collider, but instead it just shoots at the newest enemy to enter the sphere collider attached to the turret
Heres the code, mind you i havent added in little things like checking if the turret has a target yet and whatnot, mostly because ive been stuck on this for about a day and a half :\
var Target : GameObject;
var TargetList = new Array();
var DistanceVector : Vector3;
var TargetPos : Vector3;
var TurretPos : Vector3;
var ShortestDistance : float = 9999;
var Distance : float;
function Start ()
{
TurretPos = transform.position;
}
function Update ()
{
FindEnemy();
transform.LookAt(Target.transform.position);
}
function OnTriggerEnter (col : Collider)
{
if (col.gameObject.tag == "Enemy")
{
TargetList.Add(col.gameObject);
}
}
function OnTriggerExit (col : Collider)
{
if (col.gameObject.tag == "Enemy")
{
TargetList.Remove(col.gameObject);
}
}
function FindEnemy()
{
for(i=0;i<TargetList.length;i++)
{
TargetPos = TargetList*.gameObject.transform.position;*
-
DistanceVector = TargetPos - TurretPos;*
-
Distance = DistanceVector.magnitude;*
-
if(Distance < ShortestDistance)*
-
{*
_ Target = TargetList*.gameObject;_
_ ShortestDistance = TargetPos.magnitude;*_
* }*
* }*
}