Ole Albers
Ole Albers

Reputation: 9285

Calculating Shortest Distance between two GameObjects

I have two GameObjects. One VERY big, one VERY small. Think of a runway and a small plane on it. I try to determine the distance between those two objects using Vector3:

var distance=Vector3.Distance(runway.transform.position, plane.transform.position);

Now when the plane is in the middle of the runway I receive a very small value for distance (like 0.5). But at the end of the runway I receive quite high values. IMHO this is because I compare the center of both GameObjects and not the closest distance.

Is there a way to get the closest distance between those two?

(the "runway" is not in a flat angle so I can not just compare the Y-axis for this)

Upvotes: 0

Views: 2169

Answers (1)

Nimrod Segall
Nimrod Segall

Reputation: 104

If the "runway" has a collider attached to it, you can use something like ClosestPointOnBounds(Vector3 position), which returns the point on the collider bounds that is closest to "position". So something like this could work:

Collider col = GetComponent<Collider>();
Vector3 closestPoint = col.ClosestPointOnBounds(planePosition);

Can read more about this here: https://docs.unity3d.com/ScriptReference/Collider.ClosestPointOnBounds.html

Upvotes: 1

Related Questions