Having a rectangle where upper left corner, width and height is given. How can I find nearest line on that rectangle from any point?
To visualize. Having the rectangle (OK, here a square, but anyhow) ABCD. Green dots represents points and red lines intersections I want to find.

E.g. having point k I would like to find i. My current approach is as follows:
- Calculate centre of rectangle (E).
Normalize point,
Pagainst centre:Px = kx - Ex
Py = ky - EyUse atan2 on
Pto find which plane it belongs to.By plane I mean: I divide the rectangle in eight planes as with a quadrant - but divide those four in half as well. Atan2 is a special arctan variant that gives value {0, Π} for points below x-axis and {0, -Π} above x-axis.
{-PI/2, -PI} y {-0, -PI/2} A +------------|-------------.+ B | . | . | | . 3 | 2 . | | . | . | | . | . | | 4 . | . 1 | | .| . | -------------E--------------- x | . | . | | 5 . | . | | . | . 8 | | . | . | {PI/2, PI} | {0, PI/2} | . | . | | . 6 | 7 . | | . | .| D +------------|----i---------+ C | | | kThen I do a check by:
IF atan2 > PI / 4 * 3 THEN Plane 5: use A.x for x, and points y-value. ELSE IF atan2 > PI / 4 * 2 THEN Plane 6: use D.y for y, and points x-value. ...
By sample from picture that would give
atan2 < PI / 4 * 3
atan2 < PI / 4 * 2
atan2 > PI / 4 <-- OK at plane 7.
I would believe there is a more direct approach for this. Any help would be greatly appreciated. My mathematics is very rusty, but working on it.
EDIT:
OK. Looking at my nice ASCII I realized I can combine planes:
- 1 + 8 Use x from C by check on absolute value of atan2 (0 to PI/4)
- 2 + 3 Use y from A
- 4 + 5 Use x from A by check on absolute value of atan2 (PI/4*3 to PI)
- 6 + 7 Use y from C
Eliminating quite a few steps. I have to look closer at Billy's nice answer as well.
However I thought there might be a more direct approach. As in:
f(x, y, ABCD) .... => point ;)
