Efficient maths algorithm to calculate intersections

后端 未结 9 745
既然无缘
既然无缘 2020-11-28 21:40

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 someon

相关标签:
9条回答
  • 2020-11-28 22:36

    Well, mathematics and scalar products can help there.
    - Say you want to intersect segments [AB] and [CD]
    - Suppose the line intersection of the lines is M

    M is inside segment [ÅB] if and only if
    Vector(AB) . Vector(AM) >= 0
    and
    Vector(AB) . Vector(MB) >= 0

    Where the dot "." denotes a scalar product : u . v = ux * vx + uy * vy

    So, your algo is :
    - find M
    - M is inside both segment if and only if the 4 eq below are true
    Vector(AB) . Vector(AM) >= 0
    Vector(AB) . Vector(MB) >= 0
    Vector(CD) . Vector(CM) >= 0
    Vector(CD) . Vector(MD) >= 0

    Hope this helps

    0 讨论(0)
  • 2020-11-28 22:37

    Most of the answers already here seem to follow the general idea that:

    1. find the intersection of two straight lines passing the given points.
    2. determine if the intersection belong to both line segments.

    But when intersection does not occur often, a better way probably is to reverse these steps:

    1. express the straight lines in the form of y = ax + b (line passing A,B) and y = cx + d (line passing C,D)
    2. see if C and D are on the same side of y = ax+b
    3. see if A and B are on the same side of y = cx+d
    4. if the answer to the above are both no, then there is an intersection. otherwise there is no intersection.
    5. find the intersection if there is one.

    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.

    Furthermore, if you need to compare each line segment with (n-1) other line segments, precomputing step 1 for all lines saves you time.

    0 讨论(0)
  • 2020-11-28 22:42

    A simple optimization that may save you alot of time is to check the axis-aligned bounding boxes of the lines prior to getting into the intersection calculation.
    If the bounding boxes are completely disjoint then you can be certain there is no intersection.
    Of course this is dependent of the data you have. if an intersection is very likely in every check you make then you might find yourself wasting time on a check that is always true.

    0 讨论(0)
提交回复
热议问题