- Home /
How to measure the distance between two objects?
I found this question has been asked a lot of times...Most of the answers were to use the Vector3.Distance.But Vector3.Distance measures the distance between the center of gravity between two objects.
I was wondering if there is a way to measure the perpendicular distance between two objects?
Are you trying to get the distance from outside the objects? If they have a collider you can do.
public float GetOuterDistance(GameObject first, GameObject second)
{
Vector3 pointA = first.GetComponent<Collider>.ClosestPoint(second.transform.position);
Vector3 pointB = second.GetComponent<Collider>.ClosestPoint(first.transform.position);
return Vector3.Distance(pointA, pointB);
}
Also if you mean you only want distance from a single axis you can do this
public float GetXAxisDistance(Vector3 origin, Vector3 target)
{
origin.y = 0;
origin.z = 0;
target.y = 0;
target.z = 0;
return Vector3.Distance(origin, target);
}
or simply
public float GetXAxisDistance(Vector3 origin, Vector3 target)
{
return $$anonymous$$athf.Abs(origin.x - target.x)
}
Your answer
![](https://koobas.hobune.stream/wayback/20220612192236im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
WebGl error: The error was: uncaught exception: TypeError: invalid arguments 0 Answers
Unity2D - MoveTowards not working as planned 1 Answer
Translate rotation from right-handed system to left-handed system 0 Answers
Unity 2D: Reversed Gravity doesn't work 0 Answers
Unity 5 API multi thread safe? 4 Answers