What would be an efficient algorithm for calculating the intersection point of a line starting a (x,y), with an angle of θ, and a bounding rectangle with co-orindates (0,0 to w,h)? Assuming the line origin is within the box.
In basic ascii art (for a line starting at 2,6 and θ approx 9π/8):
h---------------...h,w
. ...
. ...
. ...
7 ...
6 x ...
5 / ...
4 / ...
3/ ...
2 ...
/1 ...
0 1 2 3 4 5 6 7 ... w
All variables, except θ, are integers.
Assume we parametrize the line with a variable
t, i.e. each point on the line can be written aswith constants
Then you can first calculate the cut through the vertical boundaries:
where
t1is the distance to the intersection point and[x1,y1]the point itself. Second you do the same for the upper and lower boundaries:Now you just have to select the point with less distance from your origin
[x,y].Note that this algorithm only works if the starting point is inside the bounding box, i.e.
0 <= x <= wand0 <= y <= h.