- Home /
Constantly looking for nearest object
Hello everyone. I have this script (attached to a moving character) that finds a nearest object (tower) and it works fine until the closest tower is passed by. The script does not recalculate the distance and only shows how far is the tower that was nearest after first calculation. I need the script to look for the nearest constantly and to change variable "closestTower" if closer tower is found. This is the part of my script (running in function Update()) that is responsible for finding nearest object:
var towers : GameObject[];
towers = GameObject.FindGameObjectsWithTag("Tower");
var closestTower : GameObject;
var distance = Mathf.Infinity;
for (var tower : GameObject in towers){
var curDistance = (tower.transform.position - transform.position).magnitude;
if(curDistance <= TowerNoticeRange && tower.collider.isTrigger == false){
if (curDistance < distance) {
closestTower = tower;
distance = curDistance;
}
}
}
your problem probably has to do with this line:
if(curDistance
Try remove it and see if it works, then try find out why.
if(curDistance <= TowerNoticeRange && tower.collider.isTrigger == false) was not the problem, but because of your comment I noticed that I was using "curDistance" outside the loop, insted I should have used "distance". I fixed it now, very stupid mistake of $$anonymous$$e :). You can make this comment in to an answer now.
Answer by hypnoticmeteor · Mar 10, 2015 at 08:54 AM
Your logic is wrong. You are checking distance relative to the closest tower not the user or moving body. It works fine for the first time because curDistance < infinity . After the closest tower is reached you are replacing infinity with curDistance. Thus the tower should be closer than the distance between the user and the previous closest tower for the condition "if(curDistance < distance)" to be true, which is not going to happen unless curDistance is lesser than the previous curDistance.
Try going directly under the tower GameObject and it should work the second time.
Remove distance = curDistance and there is no need to check if curDistance is less than infinity as that will always be the case. Try this should work as you expect.
Answer by siaran · Mar 09, 2015 at 07:25 PM
Where are you calling this? You'll have to do the loop in Update().
Sorry, forgot to mention that. It is in function Update(). I have edited the post and yes, I know that loops must be in this function.
Answer by d2 · Mar 09, 2015 at 08:13 PM
use: Vector3.Distance(transform.position, tower.transform.position)
Tried it (also with "if(curDistance <= TowerNoticeRange && tower.collider.isTrigger == false)" removed), it is still doing the same thing.
Answer by DiNoGames · Mar 10, 2015 at 09:25 AM
The only thing I can imagine is that you define the variable distance outside of the Update function. But this is just a guess since you didn't post the complete code of the function.