计算点和矩形盒(最近点)之间的距离 [英] calculating distance between a point and a rectangular box (nearest point)
问题描述
有一个简单的公式来计算呢?我一直对一些数学,但我只能找到一种方法来计算定向到框的中心的距离,不是针对最近点..是否有一些资源上的这个问题?
is there a easy formula to calculate this? i've been working on some math but i can only find a way to calculate the distance directed to the center of the box, not directed to the nearest point.. are there some resources on this problem?
推荐答案
下面是一个公式,避免了所有的情况下的逻辑。 (我正好是在JS现在的工作,所以这里是一个JS实现)。让 RECT = {最大值:{X:_,Y:_}分钟:{X:_,Y:_}}
和 P = {X:_,Y:_}
Here is a single formula that avoids all the case logic. (I happen to be working in JS right now, so here's a JS implementation). Let rect = {max:{x:_, y:_}, min:{x:_, y:_}}
and p={x:_, y:_}
function distance(rect, p) {
var dx = Math.max(rect.min.x - p.x, 0, p.x - rect.max.x);
var dy = Math.max(rect.min.y - p.y, 0, p.y - rect.max.y);
return Math.sqrt(dx*dx + dy*dy);
}
说明:
这打破了问题分为计算x距离 DX
和Y距离 DY
。然后使用距离公式。
Explanation:
This breaks down the problem into calculating the x distance dx
and the y distance dy
. It then uses distance formula.
有关计算 DX
,这里是如何工作的。 ( DY
类似)
For calculating dx
, here is how that works. (dy
is analogous)
看元组所提供的最大功能:(分钟-P,0,P-MAX)
。让我们来指定这个元组(A,B,C)
。
Look at the tuple being provided to the max function: (min-p, 0, p-max)
. Let's designate this tuple (a,b,c)
.
如果p被留下分钟,然后我们有P<分钟<最大,这意味着元组将评估为(+,0, - )
,所以max函数将返回正确 A =分钟 - P
。
If p is left of min, then we have p < min < max, which means the tuple will evaluate to (+,0,-)
, and so the max function will correctly return a = min - p
.
如果p是最小和最大之间,那么我们有分钟&lt; P&LT;最大,这意味着元组将评估为( - ,0, - )
。如此反复,max函数将返回正确 B = 0
。
If p is between min and max, then we have min < p < max, which means the tuple will evaluate to (-,0,-)
. So again, the max function will correctly return b = 0
.
最后,如果p是到最大值的右侧,那么我们有,分钟&lt; MAX&LT; p和元组计算结果为( - ,0,+)
。再次,Math.max正确返回 C = P - 最大
Lastly, if p is to the right of max, then we have, min < max < p, and the tuple evaluates to (-,0,+)
. Once again, Math.max correctly returns c = p - max
.
因此,原来所有的情况下,逻辑照顾的Math.max,这导致了一个漂亮的3线,控制流-free函数。
So it turns out all the case logic is taken care of by Math.max, which leads to a nice 3-line, control-flow-free function.
这篇关于计算点和矩形盒(最近点)之间的距离的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!