计算两个游戏对象之间的最短距离 [英] Calculating Shortest Distance between two GameObjects
问题描述
我有两个游戏对象.一个非常大,一个非常小.想想跑道和上面的一架小飞机.我尝试使用 Vector3 确定这两个对象之间的距离:
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);
现在,当飞机位于跑道中间时,我收到的距离值非常小(例如 0.5).但在跑道尽头,我收到了相当高的价值.恕我直言,这是因为我比较了两个游戏对象的 center 而不是 最近的 距离.
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?
(跑道"不是平角,所以我不能只是比较 Y 轴)
(the "runway" is not in a flat angle so I can not just compare the Y-axis for this)
推荐答案
如果跑道"附有对撞机,您可以使用类似 ClosestPointOnBounds(Vector3 position) 之类的东西,它返回对撞机边界上的点,即最接近位置".所以这样的事情可以工作:
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);
可以在此处阅读更多相关信息:https://docs.unity3d.com/ScriptReference/Collider.ClosestPointOnBounds.html
Can read more about this here: https://docs.unity3d.com/ScriptReference/Collider.ClosestPointOnBounds.html
这篇关于计算两个游戏对象之间的最短距离的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!