Find the better intersection of two moving objects

前端 未结 4 774
灰色年华
灰色年华 2021-02-19 07:03

I would like to optimize dramaticaly one of my algorithm, i will try to explain it the best way that i can.

The subject

We are in a 2D euclidian system at the

4条回答
  •  长发绾君心
    2021-02-19 07:24

    Without loss of generality, let O2 be located at (0,0).

    Let s and v the location and velocity vectors of O1, v2 the speed of O2, and t the time to intercept. We then have:

    |s + v * t| = t * v2
    

    By the definition of distance:

    (sx + vx * t) ^ 2 + (sy + vy * t) ^ 2 = (t * v2) ^ 2
    

    Multiplying this out and reordering terms gives:

      sx^ 2 + 2 * sx * vx * t + vx^2 * t^2
    + sy^ 2 + 2 * sy * vy * t + vy^2 * t^2
    -                           v2^2 * t^2
    = 0
    

    i.e.

      sx^2 + sy^2 + (2 * sx * vx + 2 * sy * vy) * t + (vx^2 + vy^2 - v2^2) * t^2 = 0
      \---   ---/   \------------   ----------/       \--------   ------/
          \ /                    \ /                           \ /
           c                      b                             a
    

    As you can see, this a quadratic equation in t. We can simply apply the quadratic formula to find the two possible values for t (if the equation has no solution, that's because no interception is possible). You'll probably want to use the earliest future interception, i.e. the smaller t that is > 0.

    Once you have computed the t, finding the interception point and from that the interception direction should be easy.

    To summarize, this problem can be solved in constant time, no iteration is necessary.

提交回复
热议问题