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

前端 未结 9 1732
广开言路
广开言路 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:04

    For AABBs:

    Maybe not the best performing, but certainly the simplest method:

    p = your point

    c = centre of the cube

    s = half size of the cube

    r = the point we are looking for

    v = p - c;
    m = max_abs(v);
    r = c + ( v / m * s );
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-13 07:13

    I think you need to analyze cases; there's no single formula. It's easier to illustrate in two dimensions:

    1          2          3
        +-------------+
        |             |
    4   |      0      |   5
        |             |
        +-------------+
    6          7          8
    

    The edges of the box (extended) divide the outside into 9 regions. Region 0 (inside the box) is solved by computing the distance to each edge and taking the minimum. Every point in region 1 is closest to the top left vertex, and similarly for regions 3, 6, and 8. For regions 2, 4, 5, and 7, you need to find the distance from the point to the closest edge, which is a fairly simple problem. You can determine which region a point is in by classifying it with respect to each edge. (It's easier to see how to do this by directing the edges say, counter-clockwise.) This will also tell you if the point is inside the box.

    In 3D, the logic is exactly the same except that you classify with respect to the six faces and you have more cases.

    The problem is simpler if the edges of the box are parallel to the coordinate axes.

    0 讨论(0)
提交回复
热议问题