Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if any point (or part) of a line is inside or touches a rectangle

Tags:

math

line

I want to check if a line (or any point of a line) is within a rectangle or intersects a rectangle.

I have (x0, y0) and (x1, y1) as starting and ending points of a line. Also, (ax,ay) and (bx,by) as the top-left and bottom-right points of a rectangle

For example,

     ____________
    |            |
 ---|-----       |    Result: true
    |            |
    |____________|

    /
  _/__________
 |/           |
 /            |      Result: true
/|            |
 |____________|


     ____________
    |            |
    |   -------- |   Result: true
    |            |
    |____________|    ----------     Result: false

Can anyone suggest how to do this? I dont want to know which point is that, i just want to know if its there or not.

Thanks a lot for help

like image 673
user427969 Avatar asked Jan 28 '11 01:01

user427969


People also ask

How do you determine if a point is inside or outside a rectangle?

Approach: If we observe carefully, It will be clear that for a point to be lie inside the rectangle, it should be lie inside the x-coordinate (x1, x2) of the rectangle as well as it should also lie inside the y-coordinate (y1, y2) of the rectangle.

How do you know if a point is inside a square?

If the area of one (or more) triangles has a different sign than the other ones, the point is outside the square. If all triangle areas have the same sign, the point is inside the square.

How do you know if a rectangle is inside a rectangle?

Well, by definition one rectangle is inside of another if all the points of the inner rectangle are within the outer rectangle. Using a bit of geometry you can boil it down to checking whether the two opposite corners of the inner rectangle are in the outer rectangle.


1 Answers

The first and third cases are trivial - simply return true if either endpoint of the line is within the box (i.e. > ax and ay, < bx and by).

The second presents a problem - we can't rely on the endpoints of our line anymore. In this case, we will have to test the line with each edge of the rectangle.

The equation for our line will be (x1 - x0)*x + (y1 - y0)*y + x0*y0 - x1*y1 = 0 , and we can construct a similar equation for each side of the rectangle using the corners. Following that, substituting the equation for the sides of the rectangle into our line will give us the intersection.

Finally, we check to ensure that the point is within the bounds of the side of the rectangle, and likewise within the line segment we are considering.

There is a more detailed account of this in this discussion.

like image 180
Andy Mikula Avatar answered Sep 18 '22 15:09

Andy Mikula