2D line intersection point with a bounding box
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 as
[x(t),y(t)] = [x,y] + t * [dx,dy]
with constants
dx = cos(theta)
dy = sin(theta)
Then you can first calculate the cut through the vertical boundaries:
if dx<0 then // line going to the left -> intersect with x==0
t1 = -x/dx
x1 = 0
y1 = y + t1*dy
else if dx>0 then // line going to the right -> intersect with x==w
t1 = (w-x)/dx
x1 = w
y1 = y + t1*dy
else // line going straight up or down -> no intersection possible
t1 = infinity
end
where t1
is the distance to the intersection point and [x1,y1]
the point itself. Second you do the same for the upper and lower boundaries:
if dy<0 then // line going downwards -> intersect with y==0
t2 = -y/dy
x2 = x + t2*dx
y2 = 0
else if dy>0 then // line going upwards -> intersect with y==h
t2 = (h-y)/dy
x2 = x + t2*dx
y2 = h
else
t2 = infinity
end
Now you just have to select the point with less distance from your origin [x,y]
.
if t1 < t2 then
xb = x1
yb = y1
else
xb = x2
yb = y2
end
Note that this algorithm only works if the starting point is inside the bounding box, i.e. 0 <= x <= w
and 0 <= y <= h
.
精彩评论