- Home /
Trying to use "OverlapSphere" to detect closest enemy
So I am building a firing system for a game I am working on with a small team. We have different types of moves that the player can use (direct shot, area of effect, ect.) To help simplify the process we are using an "aim assist" that fires an move at the closest enemy.
To accomplish this task I am using "OverlapSphere" to build an array of close gameObject, then calculating to find the closest one at any given point. the code I have provided work (meaning no errors/warnings) however it keeps finding itself (the player) as the closest object and setting itself to the target. Am I missing something here? Thank you.
#pragma strict
var radius: float;
var target: Transform;
function Update ()
{
MagicCalc();
if(Input.GetKeyUp("q"))
{
CannonShot();
}
}
function MagicCalc()
{
var curNearest = Mathf.Infinity;
var enemies = Physics.OverlapSphere(transform.position, radius);
var enemyNearest: Transform = null;
for(var temp: Collider in enemies)
{
Debug.Log(temp);
var tempPos = temp.transform.position;
var tempDistance = (tempPos - transform.position).sqrMagnitude;
if(tempDistance < curNearest)
{
enemyNearest = temp.gameObject.transform;
curNearest = tempDistance;
}
}
return enemyNearest;
}
function CannonShot()
{
}
Answer by whydoidoit · Apr 02, 2013 at 09:59 AM
Either apply a layer mask to your OverlapShere to ignore the player or check whether temp is the player in the loop and continue if it is:
if(temp.transform == transform) continue; //Perhaps
Your answer
