Given a rectangle (or in my example case a square) of width x and height y, which has a centre point q, how can you find the distance from q to the edge of the rectangle through point p, where p is any point in the rectangle? In this question, p is a known position (any point).
Also worth noting that the coordinates systems used is for computer graphics, so top left is 0,0 and bottom right is x,y. I have tried using trig to find the angle between q and p, then trig again to calculate the distance to the edge, but I ran into issues with trig functions in different quadrants.
Example - Example drawing with a square of size 128,128 where the length of the purple line is the goal In this instance, if p was (80, 64) then the output would be 64 (because it is a flat horizontal line from the centre to the outside) and if p was (75, 75) then the output would be ~90.51 (the line would be straight from the centre to the bottom right corner)
I am posting the outline of an algorithm as an answer, with the idea that you will fill in the spaces.
The easiest way to tackle this problem is to avoid trig functions, and restrict your attention to focusing on (x,y) coordinates. Further, the math will be much simpler if you adopt the following conventions:
The center of the rectangle has (x,y) coordinate of (0,0).
The rectangle has width $2 \times X$ and height $2 \times Y$.
The upper right hand corner has (x,y) coordinate of $(X,Y)$, and the lower left corner has coordinate $(-X, -Y).$
The easy way to tackle this is to split the algorithm into 4 cases, depending on which quadrant point P=(a,b) is in. I will assume that P is in the first (upper right) quadrant. What is needed as a first step is to pretend that you are drawing a line $L$ from the center thru point P that intersects the rectangle. All you have to do is identify the (x,y) coordinates of the intersection. Then, the Pythagorean Theorem kicks in, so you are done.
Working in case 1, you have to determine whether line $L$ will intersect the top edge or the right edge. This determination should be immediate based on your comparison of the ration (b/a) versus the ratio (Y/X). So, in case 1, you have two subcases to work with. This answer will assume that $b/a) < (Y/X)$ which means that line L will hit the right edge. The intersection point should be $\left(X,X \times \frac{b}{a}\right).$ At this point, if I'm not mistaken, you are done.