AI algorithm to “shoot” at a target in a 2d game

后端 未结 3 1284
星月不相逢
星月不相逢 2021-02-04 21:49

in my 2d game I would like to create an intelligent bot who can \"shoot\" to the player. Suppose I can pass to my bot:

actual xEnemy, yEnemy

also enemy speed a         


        
3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-02-04 21:56

    Notation: I write vectors in capital letters, scalars in lower case, and ∠V for the angle that the vector V makes with the x-axis. (Which you can compute with the function atan2 in many languages.)

    The simplest case is a stationary shooter which can rotate instantly.

    Let the target be at the position A and moving with velocity VA, and the shooter be stationary at the position B and can fire bullets with speed s. Let the shooter fire at time 0. The bullet hits at time t such that |A − B + t VA| = t s. This is a straightforward quadratic equation in t, which you should be easily able to solve (or determine that there is no solution). Having determined t, you can now work out the firing angle, which is just ∠(A − B + t VA).

    Now suppose that the shooter is not stationary but has constant velocity VB. (I'm supposing Newtonian relativity here, i.e. the bullet velocity is added to the shooter's velocity.)

    It's still a straightforward quadratic equation to work out the time to hit: |A − B + t(VA − VB)| = t s. In this case the firing angle is ∠(A − B + t (VA − VB)).

    What if the shooter waits until time u before firing? Then the bullet hits the target when |A − B + t(VA − VB)| = (tu) s. The firing angle is still ∠(A − B + t(VA − VB)).

    Now for your problem. Suppose that the shooter can complete a half rotation in time r. Then it can certainly fire at time r. (Basically: work out the necessary firing angle, if any, for a shot at time r, as described above, rotate to that angle, stop, wait until time r, then fire.)

    But you probably want to know the earliest time at which the shooter can fire. Here's where you probably want to use successive approximation to find it. (Sketch of algorithm: Can you fire at time 0? No. Can you fire at time r? Yes. Can you fire at time ½ r? No. etc.)

提交回复
热议问题