- Home /
Calculate Distance Between two Game objects
Hello I am here finding group of sphere of same tag..
For that oncollision , i have got array of all the sphere which are in contact of collided sphere..
Method i have used : var hitColliders = Physics.OverlapSphere(collision.transform.position, 0.6);
By this method , I am getting group of sphere connected to each other. But i want to find the closest sphere among this array. So i need to calculate the distance between bullet sphere and all the game objects within this array. From that i want to find minimun distance object.
But i am not getting the way to calculate distance?? Please Help me out. Thanks in advance for ur support and help..
Answer by sparkzbarca · Mar 20, 2013 at 07:31 AM
vector3.distance(sphere1.transform.position,sphere2.transform.positon)
mark as answered and have a nice day
basically you'll just want to
closestcollider = null;
distance = 999f;
foreach (collider in array)
{
if(vector3.distance(collider.transform.position,bullet.transform.position) < distance){
distance = vector3.distance(collider.transform.position,bullet.transform.position);
closestcollider = collider;
}
you'll go through the list and any time you find a collider closer than any you've found so far you'll change the distance so you know the current closest distance and change the closestcollider so you have the current closest collider. at the end you have the closest collider as well as how close it is.
I ummarked it as answer for two reasons, first it is not vector3.distance but Vector3.Distance().
Second because Distance is to be avoided if you want to optimize your game (which you should want to). Distance is based on square root which is a recursive function and can slow down if used every frame on many objects.
Ins$$anonymous$$d you may use:
Vector3 distanceSqr = (target.position - player.position).sqr$$anonymous$$agnitude;
if(distanceSqr < rangeSqr) //Within range
Your answer
Follow this Question
Related Questions
A node in a childnode? 1 Answer
How to scale an object between two values over distance 1 Answer
iTween MoveTo "Convoy" 0 Answers
How to set image in Aspect fit on Texture2D 0 Answers
grab all game objects with a distance of the object? 2 Answers