calculating distance between a point and a rectangular box (nearest point)

前端 未结 9 1737
广开言路
广开言路 2020-12-13 06:25

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 direct

9条回答
  •  死守一世寂寞
    2020-12-13 07:05

    I have been looking for this and I think I have a solution, for the case on which the box is axis-aligned (a fairly common case)

    I believe that in that case you can calculate the distance like this:

    function distance_aux(p, lower, upper)
      if p < lower then return lower - p end
      if p > upper then return p - upper end
      return min(p - lower, upper - p)
    end
    
    function distance(point, box)
      local dx = distance_aux(point.x, box.left, box.right)
      local dy = distance_aux(point.y, box.top, box.bottom)
      return sqrt(dx * dx + dy * dy)
    end
    

    This can be extended to z, of course.

提交回复
热议问题