- Home /
Working out which vector 3 is closest
If I have an AI character, who's position is stored as a Vector3 eg:
Vector3 character = new Vector3 (0,0,0,1);
and I have 3 locations also all stored as Vector3's
vector3 location1 = new Vector3(1,0,0,1); vector3 location2 = new Vector3(1,1,1,1); vector3 location3 = new Vector3(0,1,1,0);
what I want to do is change the characters behaviour based on which V3 location its closest too. I realise I can do this manually, by just checking the distance, but is there a neater solution to find the closest variable? I had considered putting them all in a 2D list looping through all the distances and then sorting. but Im wondering if there is a better aproach.
since when does a Vector3 has 4 parameter?
$$anonymous$$y approach would be to save all location in a Vector3 array and write the distances of the location to your AI (Vector3.Distance ()) into a float array and use $$anonymous$$athf.$$anonymous$$in() on that whole array to find the lowest distance.
Then you can hookup what index of the distance array the value matches and "poof" -> you have your Desired location
Answer by HarshadK · Jun 13, 2014 at 11:24 AM
You can get the distance between character and each of these three locations using Vector3.Distance and then compare these three output distances to find the closest one to the character using the Mathf.Min.
And geting the closest object from a array is a question that answers the same question as your but with variable number of game object's position instead of direct Vector3's.
Also check the Compare distance loop from answer of this question: GameObject.Find closest ??
Your answer