对于比赛我开发我需要一个算法,可以计算交叉点。我已经解决了这个问题,但我已经做它的方式是非常讨厌的,我希望有人在这里可能有一个更好的解决方案。
For a game I am developing I need an algorithm that can calculate intersections. I have solved the problem, but the way I have done it is really nasty and I am hoping someone here might have a more elegant solution.
一对重present它们之间的连线的终点点。鉴于两对点,做画线相交,如果是这样,在什么时候?
A pair of points represent the end points of a line drawn between them. Given two pairs of points, do the drawn lines intersect, and if so, at what point?
因此,例如调用线(AX,AY) - (BX,BY)和(CX,CY) - (DX,DY)
So for example call the lines (A.x, A.y)-(B.x, B.y) and (C.x, C.y)-(D.x, D.y)
谁能想到了解决办法?在任何语言中的解决方案就可以了。
Can anyone think of a solution? A solution in any language will do.
编辑:有一点我应该更清楚,该算法必须返回false,如果交点超出线段的长度。 I.E.这是不是一种相贯线: lines.gif
A point I should have made clearer, the algorithm must return false if the point of intersection is beyond the lengths of the line segments. I.E. this isn't an intersecition: lines.gif
推荐答案大多数问题的答案已经在这里似乎遵循的总体思路是:
Most of the answers already here seem to follow the general idea that:
但是,当路口不经常发生,更好的方法可能是扭转这些步骤:
But when intersection does not occur often, a better way probably is to reverse these steps:
请注意:做第2步,只是检查(赛扬 - 一(CX) - b)和(240 - 一(DX) - B)具有相同的符号。步骤3是类似的。步骤5是从两个等式只是标准的数学。
Note: to do step 2, just check if (C.y - a(C.x) - b) and (D.y - a(D.x) - b) have the same sign. Step 3 is similar. Step 5 is just standard math from the two equations.
此外,如果你需要在每个线段与(N-1)等线段,precomputing步骤1中的所有线路节省您的时间进行比较。
Furthermore, if you need to compare each line segment with (n-1) other line segments, precomputing step 1 for all lines saves you time.
更多推荐
高效的数学算法来计算交点
发布评论