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
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With