- Home /
detect objects around player with a predefined distance
hi there friends i have a small problem here is the details:
1-i have a script to look for all objects with tag "Enemy" 2-they will be moving and will be a lot of them (about 100). 3-i want to draw a gui box(For now) around each object that is in 200 range only. 4-my script only detect 1 nearest object , i want it to track all objects around the player with a distance of 200 units only.
here is the simple script:
function searchForEnemy() {
var gos : GameObject[];
gos = GameObject.FindGameObjectsWithTag("Enemy");
var closest : GameObject;
var distance = Mathf.Infinity;
var position = transform.position;
// Iterate through them and find the closest one
for (var go : GameObject in gos) {
var diff = (go.transform.position - position);
var curDistance = diff.sqrMagnitude;
if (curDistance < distance) {
closest = go;
distance = curDistance;
if(distance < searchRange){
target = closest;
}
}
}
}
thanks in advanced
Comment
Best Answer
Answer by MigLeader · Jul 21, 2014 at 05:27 AM
i found the solution for the problem , i used (Physics.OverlapSphere) , here is the script for anyone having the same problem:
#pragma strict
private var lastPosition : Vector3;
var adjstGUI : Vector2;
var mask : LayerMask = -1;
var hitColliders : Collider[];
function Update () {
hitColliders = Physics.OverlapSphere(transform.position, 100 , mask.value);
//for (var i = 0; i < hitColliders.Length; i++) {
//if(hitColliders[i].gameObject.tag == "Enemy"){
//}
//}
}
function OnGUI () {
for (var i = 0; i < hitColliders.Length; i++) {
if(hitColliders[i] != null){
if(hitColliders[i].gameObject.tag == "Enemy"){
lastPosition = Camera.main.WorldToScreenPoint(hitColliders[i].gameObject.transform.position);
GUI.Box(Rect(lastPosition.x + adjstGUI.x, -lastPosition.y + adjstGUI.y + Screen.height, 80,80),"");
}
}
}
}