- Home /
Finding the closest obstacle to you when you are an obstacle.
Hi. I'm trying to think of a way to find all obstacles in my game that use the obstacle tag. The confusing part is that my player is an obstacle to other players, but there is no point in counting yourself as an obstacle, so I need to exclude myself in this script. Have any idea how? All I need to know is the closest obstacle to me other than myself.
function FindThatObstacle():GameObject{
var gos:GameObject[];
gos=GameObject.FindGameObjectsWithTag("Obstacle");
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;
}
}
return closest;
}
I'm also trying to get it to use Vector3.Dot() to compare the forward direction ins$$anonymous$$d, but one thing at a time.. so basically the nearest obstacle in front of you and the ones behind ignored.
Answer by Bunny83 · May 03, 2012 at 10:41 AM
// [...]
var position=transform.position;
// Iterate through them and find the closest one
for (var go : GameObject in gos) {
if (go.transform != transform) {
var diff=(go.transform.position - position);
var curDistance=diff.sqrMagnitude;
if (curDistance<distance) {
closest=go;
distance=curDistance;
}
}
}
This should do the trick ;) I'm not sure if UnityScript knows continue
but it's a quite basic keyword so it should work. I'm a C# user ;)
Hmm... it still seems to return the closest gameobject which is it's self.
That doesn't make sense ;) Are you sure UnityScript compiles the script? No errors? You could also invert the condition and surround all the code with it. I'll change the example...
Have you tried printing the name of the closest object? Also make sure any child objects of your player arn't tagged "Obstacle". They would be found as well.
You could also check like this
if (go.transform.IsChildOf(transform))
continue;
IsChildOf checks if the object is a child, deep child or the transform itself just to be on the sure side ;)
Your answer
Follow this Question
Related Questions
How do I access the object the script is attached to? 3 Answers
a one time script 1 Answer
please help 1 Answer
0xFEFF error im new PLEASSE help. Script error 1 Answer
Instantiate cloned prefab to local position of an empty object 1 Answer