find the distance of a point from the sides of a rectangle

1.1k Views Asked by At

I would like to find the distance of a point from the sides of a rectangle.

here is various examples:

enter image description here

t(x,y) is a point within the rectangle (WxH). We have two angles (1-3 angle is 90 and for Fig 4, angle is theta). The main concern is in figure 1 and finding d = d1+d2.

For other figures, the radius of root(w^2+H^2) can be used as an approximation.

I tried for 4 hours but non of them worked.

I thought of changing the pivot to center of w/2, x/2 and do my calculation. then return it back to t with (w/2-x, h/2-y) or something like that.

As I mentioned, figure 4 is the best thing to describe the issue. however, I will be more happy with the solution with Figure 1.

Thanks

1

There are 1 best solutions below

0
On BEST ANSWER

I found the answer for figure 1 which it can also be used to cover figure 2 and 3 if theta set to zero.

M = (W/2, H / 2)
M = (M.scale( + Cos(ang), + Sin(ang))).absBoth();

T = (tx, ty)
T = (T.scale( - Cos(ang), - Sin(ang))).getRadius(); // using Pythagoras

d1 = (M + T).getRadius();

d2 = (a, b).getRadius();

I am working on figure 4. and I think it is the same concept. I need to rotate the rect(a, b) to -angle and then find its radius. I mean d2 = rect(a, b, -ang + theta).

EDIT: this is the final code I got as my solution.

private double getRectDistance(PointD wh, PointD xy, int ang) {
        double q = Math.toRadians(ang);
        return wh.scale(Math.cos(q), Math.sin(q)).abs().move(xy.scale(Math.cos(q), Math.sin(q)).Inverse()).getRadius();
    }

And finally (for Fig. 4 ):

d1 = getRectDistance(wh.middle(), (0,0), angle);
d2 = getRectDistance(ab.middle(), (0,0), -angle+theta);

distance = d1 + d2