-1

i try to to make an AI in C# (with unity) that can predict the estimated position of a moving object to hit it with a bullet the moving object have a movement speed of 5f and the bullet have a speed of 7f

my problem is that the time my bullet travel to my estimated position my "enemy" already moved further and the bullet don't hit

do you know a formula or code that i can adapt to improve my targeting AI ? (already looking for that in google but don't find anything usefull)

thank

Pben
  • 1,081
  • 7
  • 12

1 Answers1

3

An answer to your question from unreal engine forums

Here is the top answer from there in case the link dies. I did not write this code I simply found it with a quick google of your problem which you stated you already tried.

Link answer:

Get the "velocity" of the target player. Multiply by the time the bullet will take to travel to the target. Then get the position of the target, add the velocity*time vector, and that's the position you should aim at. You can either hard-code the travel time (half a second, or whatever,) or you can in turn measure the distance between AI and player, and divide by bullet travel time, to come up with an approximate travel time. You can also apply a differential equation to calculate the exact time of impact and exact direction, but that requires a little more math and is slightly harder to write out, so I think the above will work best for you.

Simply:

Distance = Length(Target_Position - Firing_Position)
Time = Distance / Bullet_Speed
Predicted_Position = Target_Position + (Target_Velocity * Time)
NPhillips
  • 505
  • 4
  • 19
  • it's what i already do but the time take by the bullet increase the Distance (or decrease). For a more precise aiming i need to make differential equation (never used it) ? – Pben Jun 12 '17 at 09:59
  • I am confused with what you mean by that. The formula above takes into account the speed of the bullet. Is it because your bullet is actually accelerating or deaccelerating? – NPhillips Jun 12 '17 at 10:04
  • this formula work well if the bullet move very fast but if (like in my case) the time is high the Distance change more than the size of my bullet (thank for the fast answers) – Pben Jun 12 '17 at 10:11
  • If there are no way to estimate more precisely i can make a loop to reduce the error but peraps there are a better way to resolve that – Pben Jun 12 '17 at 10:22