According to Daniel, in his answer, there is no easy way to modify the below function so I bit the bullet and started from scratch. Solution is below (as an answer). Actually, ignore my answer. See Tom Sirgedas’ answer it’s a lot shorter.
I need to modify the solution found here: Calculate a vector from the center of a square to edge based on radius, that calcs the vector from the center of a rectangle, to work for any point within the rectangle.
Here’s the previous solution, from the link:
double magnitude;
double abs_cos_angle= fabs(cos(angle));
double abs_sin_angle= fabs(sin(angle));
if (width/2*abs_sin_angle <= height/2*abs_cos_angle)
{
magnitude= width/2/abs_cos_angle;
}
else
{
magnitude= height/2/abs_sin_angle;
}
double check_x= x + cos(angle)*magnitude;
double check_y= y + sin(angle)*magnitude;
check_x and check_y return the point on the edge of the rectangle that a line drawn from the center, at angle, will intersect.
It’s a while since I went to school, so I blindly tried replacing width/2 and height/2 with the point I’m interested in. Unfortunately that didn’t work.
Any ideas?
ETA:
This blind modification always returns the correct result if the line intersects the rectangle at the Top or Left. Depending on the quadrant the originating point is in, it returns a point too far away or too close when the line intersects the Right or Bottom.
Let’s say the rectangle is defined by (x1,y1,x2,y2) and let’s say the ray starts at (px,py).
Let vx = cos(angle)
Let vy = sin(angle)
Traveling a distance of t along the ray will bring you to the point (px+tvx, py+tvy).
Traveling along the ray,
So, there are four possible solutions for t. The correct value of t (among the four) is the smallest positive one. The actual intersection is at the point (px+tvx, py+tvy). Just be careful not to divide by zero!