Consider a rectangle $ABCD$, with the $A$ point in the $(0,0)$ position. Based on a point on the edge of the rectangle ($E$ in the picture) and a point inside the rectangle (multiple examples in the picture - $F$, $G$ and $H$) find the opposite point on the same rectangle (in my example $I$, $J$ and $K$).
This is how I solve it, using Slope–intercept form:
- if $E$ is on the bottom edge:
- calculate slope $m$ between $EF$, $EG$ or $EH$
- calculate $y0$
- calculate $x$ for $y==height==b==d$
- if $x$ is negative, then set $x=0$ and $y=y0$ ($I$ in my example)
- if $0<x<width$ then use x and y ($J$ in my example)
- if $x>width$ then set $x=width$ and calculate y ($K$ in my example)
I use similar logic for other three scenarios (when edge point is on left edge, top edge or right edge). I feel there should be an easier solution, which doesn't care on which edge the starting point is. My solution is very complex and error prone (additional exception are vertical lines where you cannot calculate $slope$). Any better ideas?