Finding closest edge to a point on a rectangle

184 Views Asked by At

In the image below I have a rectangle (with corners 1-4). I have a blue point. I'm trying to find which side is closest to this point. Finding one of the corners (that make up the side) seems easy. As far as I can tell, the closest point must necessarily be one of the two points that make up the side.

The second corner... not so much. Given the first point, the second obviously has to be one of the adjacent ones. What I'm requesting help with is a means to determine which direction I must rotate to get the second point. I expect there is some relationship between the corner and the point that I'm simply not seeing.

The use case here is for a computer program, but it feels like there must be a mathematical solution. I apologize if this is is the incorrect place for this.

https://i.stack.imgur.com/j6cPb.png

2

There are 2 best solutions below

1
On BEST ANSWER

There is actually no need to find the closest corner. By drawing(and extending infinitely far) the diagonals of the rectangle, you can split the screen(assuming rectangle and point are both on the screen) into areas where two points in the same area are closest to the same side. This is probably easier seen with a visualization:

rectangle+diagonals

Any point in the top region is closest to the top side, any point in right region is closest to the right side, etc. It can be proved by some pretty basic geometry that this is the case, but it should be intuitively obvious.

Here is some pseudocode to determine which side is the closest. The pseudocode assumes that the rectangle is centered at $(0, 0)$, the point lies outside the rectangle, and rectangle's sides are parallel to the axes(the geometry above does not assume the last point):

point = (x, y)
bottom left corner = (-a, -b)
top right corner = (a, b)

if x=0:
    closest side = (top if y>0) (bottom if y<0)
else:
    if abs(y/x) > b/a:
        closest side = (top if y > 0) (bottom if y < 0)
    else:
        closest side = (left if x < 0) (right if x > 0)

Some slight modifications could be made if the point is inside the rectangle.

0
On

The four lines on which the sides of the rectangle lie divide the plane into $9$ regions (one is the interior of the rectangle). You can use the inequalities you get by putting the blue point coordinates into the equations for those four lines to determine which region contains the blue point. Once you know that the rest should be easy.

(This answers the question in the title and the first line - finding the closest edge. )