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

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

    Let's say that the point is named P and ABCD is our rectangle. Then the problem can be decomposed into the following set of subproblems:

    (1) Develop a function dist(P, AB) that calculates the distance between a point P and an arbitrary segment AB.

    (2) Calculate four distances between your point P and each side of the rectangle (each side is a segment) and take the shortest of the four

      distance = min(dist(P, AB), dist(P,BC), dist(P, CD), dist(P, DA))
    

    That's your answer.

    Now, we need to know how to calculate the distance between point P and an arbitrary segment AB, i.e. how to calculate dist(P, AB). This is done as follows

    (1) Perform a perpendicular projection of the point P to the line AB. You get the new point P' on AB.

    (2) If P' lies between A and B, then dist(P, AB) is the distance between P and P'.

    (3) Otherwise, dist(P, AB) is the distance between P and either A or B, whichever is shorter.

    That's it. There are some obvious ways to optimize the procedure, but even if implemented literally, it will work very well already.

    P.S. Of course, one can ask how to perform a projection of a point to a line. I'll leave it as an exercise to the reader :)

提交回复
热议问题