Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if line segment intersects a rectangle?

If you have 2 points, (x1, y1) and (x2, y2), which represent two opposite corners of a rectangle, and 2 other points, (x3,y3) and (x4,y4), which represent 2 endpoints of a line segment, how can you check if the line segment intersects the rectangle?

(The line segment is just the segment contained between the given endpoints. It is not an infinite length line defined by those two points.)

like image 460
omega Avatar asked Apr 24 '13 23:04

omega


People also ask

How do you know if a line segment intersects?

If f = 0 for any point, then the two lines touch at a point. If f1_1 and f1_2 are equal or f2_1 and f2_2 are equal, then the lines do not intersect. If f1_1 and f1_2 are unequal and f2_1 and f2_2 are unequal, then the line segments intersect.

How do you check if a line intersects a polygon?

Line crosses the polygon if and only if it crosses one of its edges (ignoring for a second the cases when it passes through a vertex). So, in your case you just need to test all edges of your polygon against your line and see if there's an intersection.

Does a rectangle have line segments?

In geometry, a line segment is a part of a line that is bounded by two distinct endpoints. So, a rectangle with four sides or it could be said as a rectangle with four line segments.

How do you find where a line segment intersects a circle?

To determine the position of a line with respect to a circle, all we need to do is find its distance from the center of the circle, and compare it with its radius. Then, if the distance is less than the radius, the line must intersect the circle at two distinct points.


1 Answers

One very simple option would be to use a standard algorithm for checking whether two line segments intersect to check whether the line segments intersects any of the four line segments that make up the corners of the box. It's computationally very efficient to check if two line segments intersect, so I would expect that this could run very quickly.

Hope this helps!

like image 102
templatetypedef Avatar answered Sep 19 '22 14:09

templatetypedef