简体   繁体   中英

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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM