Hey!
I recently needed a method that…well, the title says it all. This method takes the x, y, width and height values of a rectangle, and the two endpoints of a line, and returns true if the line intersects the rectangle range at all.
Here ya go
public static boolean rectangleIntersectsLine(double x, double y, int w, int h, double lx1, double ly1, double lx2, double ly2) {
//determine values to be used in the equation for the line
double m = (ly2-ly1)/(lx2-lx1);
double p = lx1, q = ly1; //p = the offset from left side of screen, q = offset from bottom
//if point l2 is closer to x = 0 than l1, set p and q to lx2's coordinates
if (lx2 < lx1) {
p = lx2;
q = ly2;
}
//test if both end points of line are on left side, right, top, or bottom
//if any is true, then the line does not intersect
boolean on_left = (lx1 < x && lx2 < x), on_right = (lx1 > x+w && lx2 > x+w),
on_top = (ly1 < y && ly2 < y), on_bottom = (ly1 > y+h && ly2 > y+h);
if (!on_left && !on_right && !on_top && !on_bottom) {
if (((y < (m*(x-p)+q)) && (y+h > (m*(x-p)+q)))
|| ((y < (m*(x+w-p)+q)) && (y+h > (m*(x+w-p)+q)))) { //if left side or right side of rectangle intersects line
return true;
}
if ((x < (((y-q)/m)+p) && x+w > (((y-q)/m)+p))
|| (x < (((y+h-m)/q)+p) && x+w > (((y+h-q)/m)+p))) { //if top side or bottom side of rectangle intersects line
return true;
}
}
return false;
}