I have checked out this question, but the answer is very large for me:
How to know if a line intersects a plane in C#? - Basic 2D geometry
Is there any .NET method to know if a line defined by two points intersects a rectangle?
public bool Intersects(Point a, Point b, Rectangle r)
{
// return true if the line intersects the rectangle
// false otherwise
}
Thanks in advance.
The simplest computational geometry technique is to just walk through the segments of the polygon and see if it intersects with any of them, as it then must also intersect the polygon.
The only caveat of this method (and most of CG) is that we have to be careful about edge cases. What if the line crosses the rectangle at a point - do we count that as intersection or not? Be careful in your implementation.
Edit: The typical tool for the line-intersects-segment calculation is a
LeftOf(Ray, Point)
test, which returns if the point is the to the left of the ray. Given a linel
(which we use as a ray) and a segment containing pointsa
andb
, the line intersects the segment if one point is to the left and one point is not:Again, you need to watch out for edge-cases, when the point is on the line, but depends how you wish to actually define intersection.
For Unity (inverts y!). This takes care of division by zero problem that other approaches here have:
Unfortunately the wrong answer has been voted up. It is much to expensive to compute the actual intersection points, you only need comparisons. The keyword to look for is "Line Clipping" (http://en.wikipedia.org/wiki/Line_clipping). Wikipedia recommends the Cohen-Sutherland algorithm (http://en.wikipedia.org/wiki/Cohen%E2%80%93Sutherland) when you want fast rejects, which is probably the most common scenario. There is a C++-implementation on the wikipedia page. If you are not interested in actually clipping the line, you can skip most of it. The answer of @Johann looks very similar to that algorithm, but I didn't look at it in detail.
Brute force algorithm...
First check if the rect is to the left or right of the line endpoints:
Then, if the above wasn't enough to rule out intersection, check if the rect is above or below the line endpoints:
Then, if the above wasn't enough to rule out intersection, you need to check the equation of the line,
y = m * x + b
, to see if the rect is above the line:Then, if the above wasn't enough to rule out intersection, you need to check if the rect is below the line:
Then, if you get here:
N.B. I'm sure there's a more elegant algebraic solution, but performing these steps geometrically with pen and paper is easy to follow.
Some untested and uncompiled code to go with that:
I took HABJAN's solution, which worked well, and converted it to Objective-C. The Objective-C code is as follows:
Many thanks HABJAN. I will note that at first I wrote my own routine which checked each point along the gradient, and I did everything I could do to maximize performance, but this was immediately far faster.