Currently my script will target the first ‘Target’ in it’s range (furthest) but will not target the closest target which is what I’m trying to get done. Any help would be appreciated.
//loop the following section every 0.1second indefinitely
while(true){
//check there's no target or the target is already out of range
if((target==null || !target.gameObject.active) || Vector3.Distance(target.position, thisT.position)>range){
//check for all unit within range
var allTargets=Physics.OverlapSphere(thisT.position, range, layerMask);
//if there are target within range
if(allTargets.length!=0) {
//just assign the first target
target=allTargets[Random.Range(0, allTargets.length)].transform;
targetCom=target.gameObject.GetComponent.<Creep>();
}
//else dont set any target
else target=null;
}
yield WaitForSeconds(0.1);
The function should actually just give you a target, regardless of its distance (since Random.Range just returns a random number between min and max, the range has nothing to do with the distance).
To get the closest target, either sort your target array and get the first entry or just iterate over the list and check which target is the closest. Try something like
if(allTargets.length!=0) {
var minSqrDistance = range*range; // if sqrmagnitude > range^2 it would be out of reach
var currentTargetIndex = 0;
for(var i = 0; i < allTargets.length; i++)
{
var sqrMag = (thisT.position - object.transform.position).sqrMagnitude;
if(sqrMag < minSqrDistance)
{
minSqrDistance = sqrMag;
currentTargetIndex = i;
}
}
target=allTargets[currentTargetIndex].transform;
targetCom=target.gameObject.GetComponent.<Creep>();
}
Note: not sure if this will work - I’m not a JavaScript guy - but it should give you an idea.
Ok, update on what I’ve done. I found that using JS was a bit too much for me to try to wrap my head around so I decided to rebuild my script (which wasn’t mine to begin with). I’m currently working with C# and I haven’t had any issues. Thank you very much for the assistance and answers.