Is there a way to calculate a perfect projectile "leading," algorithm?

440 Views Asked by At

I was programming an AI to throw things at the player. The AI would have to lead the player's movement in order to accurately hit them. I thought this would be a simple trig problem to calculate the "target," spot to aim for, but it turned out to be a lot more complicated than I thought.

This is more of a mental exercise than a problem I'm actually trying to solve, as IRL you don't want a perfect AI, so rough approximations are actually better for gameplay, but I am still curious thought if I wanted to do a perfect leading AI, how would that be calculated

Setup:

  • There is an enemy, and the player, both positions represented by 2D vectors
  • The enemy is trying to throw a projectile that travels at a constant speed
  • The enemy needs to calculate a target position (also represented by a 2D vector) ahead of the player to aim at.
  • The target point should be the one that takes the least amount of travel time, as that minimizes the chance of the player's velocity will change.
  • We assume that the enemy position (PENEMY), player position (PPLAYER), player velocity (VPLAYER), and projectile speed (speed) are known will remain constant during the travel time of the projectile.

So far I've figured it out to the point of

$$ \vec{TARGET} = \vec{PENEMY} + (\vec{VPLAYER} * travelTime) $$ $$ travelTime = ||\vec{PPLAYER} \hspace{5pt} \vec{TARGET}|| * speed $$

My first thought was to re-arrange the first equation to solve for travelTime and then use substitution, but I don't think I can do that for vectors like this. The main problem seems to be that the equation seems a bit paradoxical IE: In order to know the target, we need to know the travel time, but in order to know the travel time, we need to know the target.

Practically it seems like I could assume an initial target of PPLAYER + VPLAYER, and then do multiple iterations of both equations, which should get me pretty close to an exact result, but I'm curious if there is a more rock solid answer.

I'm pretty decent at Trig, and know a little calculus (though I haven't practiced it in years). Since we "know," almost all variables at time of calculation, it seems like there should be a way to figure out a definite answer, but this one is a bit beyond me.