I'm aware that this is probably not the best place to post this but no other place has helped me thus far. I was looking over some code and I found this very poorly commented line intersection function...
inlinebool LineIntersection2D(Vector2D A,
Vector2D B,
Vector2D C,
Vector2D D)
{
double rTop = (A.y-C.y)*(D.x-C.x)-(A.x-C.x)*(D.y-C.y);
double sTop = (A.y-C.y)*(B.x-A.x)-(A.x-C.x)*(B.y-A.y);
double Bot = (B.x-A.x)*(D.y-C.y)-(B.y-A.y)*(D.x-C.x);
if (Bot == 0)//parallel
{
returnfalse;
}
double invBot = 1.0/Bot;
double r = rTop * invBot;
double s = sTop * invBot;
if( (r > 0) && (r < 1) && (s > 0) && (s < 1) )
{
//lines intersect
returntrue;
}
//lines do not intersect
returnfalse;
}
I know of cross and dot products and I'm sure something along those lines is going on here but my understanding is likely minimal. I also figured that A and B are points on the first line and C and D are the points of the second. The closest thing I found that could be helpful is this : http://stackoverflow.com/questions/563198/how-do-you-detect-where-two-line-segments-intersect
However I still don't understand what is going on. Can someone here please help me out?
cross() refers only to the magnitude with sign of the product.
1 2 3
rtop = cross(D-C, A-C)
sTop = cross(B-A, A-C) = -cross(A-B, A-C)
Bot = cross(B-A, D-C) == r x s
your `r' and `s' would be `t' and `u' in SO answer.
Another way
Suppose that the segments intersects, if you are a segment you'll see both the endpoints of the other segment to different sides of you.
To check the side, you may use the sign of the cross product, then it follows that