How to check the intersection between a line and a rectangle?

The title says everything, I searched and could not find anything that would be straightforward and accurate. How to take a line with points (x1, y1) and (x2, y2) and check its intersection between the rectangle (xR, yR)? I saw in the Line2D package that there are some intersection methods, but not sure how to set it all up. Can someone show me the correct way to configure it to check for intersection (collision)?

+7
source share
3 answers

Use the available classes from the 2D Graphics API.

Rectangle r1 = new Rectangle(100, 100, 100, 100); Line2D l1 = new Line2D.Float(0, 200, 200, 0); System.out.println("l1.intsects(r1) = " + l1.intersects(r1)); 

That this does not tell you where ...

+5
source

The rectangle has 4 lines. You can calculate the intersection between your line and the four lines of the rectangle.

given the equations of two lines, they intersect when x and y are equal.

y = m1x + b1 y = m2x + b2

the solution to the equation you should get:

x = b2 - b1 / (m1 - m2);

Note that if m1 == m2, the lines are parallel and never intersect, be aware of the division by 0. In this case.

Then, since you are dealing with segments exceeding infinite lines, check if the intersection does not intersect inside your segments (check if both X and Y correspond to the boundaries of each segment).

+4
source

Returns null if lines do not intersect. Changed some code from another answer to a similar question to make it Java. Did not bother to see how / why it works, but whether it does the work that I needed.

 static Point get_line_intersection(Line2D.Double pLine1, Line2D.Double pLine2) { Point result = null; double s1_x = pLine1.x2 - pLine1.x1, s1_y = pLine1.y2 - pLine1.y1, s2_x = pLine2.x2 - pLine2.x1, s2_y = pLine2.y2 - pLine2.y1, s = (-s1_y * (pLine1.x1 - pLine2.x1) + s1_x * (pLine1.y1 - pLine2.y1)) / (-s2_x * s1_y + s1_x * s2_y), t = ( s2_x * (pLine1.y1 - pLine2.y1) - s2_y * (pLine1.x1 - pLine2.x1)) / (-s2_x * s1_y + s1_x * s2_y); if (s >= 0 && s <= 1 && t >= 0 && t <= 1) { // Collision detected result = new Point( (int) (pLine1.x1 + (t * s1_x)), (int) (pLine1.y1 + (t * s1_y))); } // end if return result; } 
+4
source

All Articles