Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if two line segments are colliding (only check if they are intersecting, not where) [closed]

Tags:

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.

like image 228
Mike Avatar asked Aug 15 '11 19:08

Mike


People also ask

How do you check if two lines are intersecting or not?

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.

Can the intersection of two lines be a line segment?

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.

Are any two lines if and only if they do not intersect even if it is extended in both directions?

Parallel lines are lines in a plane that are always the same distance apart. Parallel lines never intersect.


1 Answers

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.

like image 95
Beta Avatar answered Sep 21 '22 15:09

Beta