I need a fast algorithm for checking if two non-infinite lines are crossing. Have to be fast because it'll run on a cell phone a lot.
The algorithm do only have to return yes or no, it does not have to find out exactly where the lines cross!
I have looked here: How do you detect where two line segments intersect? But that thread is a jungle, people keep saying that "this is the answer" but then two other guys say that it is incorrect because of this-and-that bug.
Please help me find a good and working algorithm for this.
Just to be clear: I need a function that you give...lineApointAx
lineApointAy
lineApointBx
lineApointBy
lineBpointAx
lineBpointAy
lineBpointBx
lineBpointBy
...and that returns true or false depending on if the two lines cross or not.
I would appreciate if you answered with (pseudo-)code, not formulas.
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.
When two lines, rays, or line segments intersect, they have one common point; in this case, the line segments intersect since they meet at the center of the windmill's blades. In the figure below, point (3,4) is the intersection of line x = 3 and line y = 4 since that is where the two lines cross.
Parallel lines are lines in a plane that are always the same distance apart. Parallel lines never intersect.
It is necessary and sufficient that the two ends of one segment are on different sides of the other segment, and vise-versa. To determine which side a point is on, just take a cross-product and see whether it's positive or negative:
(Bx - Ax)(Py - By) - (By - Ay)(Px - Bx)
EDIT:
To spell it out: suppose you're looking at two line segments, [AB] and [CD]. The segments intersect if and only if ((A and B are of different sides of [CD]) and (C and D are on different sides of [AB])).
To see whether two points, P and Q, are on different sides of a line segment [EF], compute two cross products, one for P and one for Q:
(Fx - Ex)(Py - Fy) - (Fy - Ey)(Px - Fx)
(Fx - Ex)(Qy - Fy) - (Fy - Ey)(Qx - Fx)
If the results have the same sign (both positive or both negative) then forget it, the points are on the same side, the segments do not intersect. If one is positive and the other negative, then the points are on opposite sides.
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