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

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

问题描述

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

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 <最大<p,元组计算结果为 (-,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天全站免登陆