intersection

How to test if a line segment intersects an axis-aligned rectange in 2D? The segment is defined with its two ends: p1, p2. The rectangle is defined with top-left and bottom-right points.
This may not be a particularly smart way, but anyway..
If line intersects with rect, it intersects with two walls of it.
Lets say line is defined by points p1, p2 and rect is defined by r1, r2.
1
2
3
4
5
6
//find a point where line intersects with line y = r1.y
intersection.x = p1.x + (p1.x-p2.x)*(p1.y-r1.y)/(p1.y-p2.y);//lerp
//don't forget to check if p1.y-p2.y != 0
if(intersection.x >= r1.x && intersection.x <= r2.x) return true;//check if intersection is between r1 and r2
//note that this line assumes, that r1 < r2
//repeat the process for each wall 

This algorithm really checks for intersections with a line, and not a segment of it. One way to solve this would be to add
1
2
if(r1.y >= p1.y && r1.y <= p2.y) ...
//note that this line assumes, that p1 < p2 
to your code
Topic archived. No new replies allowed.