计算点和矩形框(最近点)之间的距离 [英] calculating distance between a point and a rectangular box (nearest point)

查看:26
本文介绍了计算点和矩形框(最近点)之间的距离的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一个简单的公式来计算这个?我一直在做一些数学运算,但我只能找到一种方法来计算指向盒子中心的距离,而不是指向最近的点..这个问题有一些资源吗?

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 = {max:{x:_, y:_}, min:{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)

查看提供给 max 函数的元组:(min-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 在 min 的左边,那么我们有 p <最小max,这意味着元组将评估为 (+,0,-),因此 max 函数将正确返回 a = min - 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 在 min 和 max 之间,那么我们有 min <p<max,这意味着元组将评估为 (-,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 在 max 的右边,那么我们有 min <最大(-,0,+).再一次,Math.max 正确返回 c = p - max.

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.

事实证明,所有 case 逻辑都由 Math.max 处理,这导致了一个不错的 3 行、无控制流函数.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆