开发者

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

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broa开发者_高级运维d, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. Closed 11 years ago.

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.


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're two given points are (X1,Y1) and (X2,Y2), imagine both are infinite lines, not just segments:

  1. Determine the formula for both (see: http://en.wikipedia.org/wiki/Linear_equation#Two-point_form)

  2. Determine the intersection point for the two lines (see: http://zonalandeducation.com/mmts/intersections/intersectionOfTwoLines1/intersectionOfTwoLines1.html)

  3. If X1 < intersectionX < X2 and Y1 < intersectionY < Y2, then yes, the segments intersect.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜