In a 2d side-view scenario I have two riflemen aiming at each other. By normalizing the x and y difference they know the direct path to the enemy.

However, gravity will pull the projectiles downwards, so aiming straight for the enemy is obviously useless.

Any interesting ideas for AI-logic when it comes to adding a correction based on world.gravity (which is a "force" in y-pixels per physics tick) and enemy.path (libgdx Vector2 with the X and Y difference to the enemy. Weapon.muzzleVelocity could also be factored in (double, speed in pixels after the shot is fired.

I've been thinking of two things:

Option 1 - Magic numbers

The X distance is multiplied by a magic number (such as gravity) to produce a reasonable close result to an aiming offset. Possibly also factoring in Y-distance, but in most cases, the Y distance should be close to 0.

Pros: Simple, easy to implement, quick, low calculation overhead

Cons: Boring, A bit too arcade for my taste with a very static result, Been done before countless times including by me in previous projects

Option 2 - Firing table

AI trial and error, basically. Each time the unit fires, the X (and Y?) distance of that shot is recorded with the offset used, and the result (hit vs too low vs too high) is registered. Each time the unit fires it'll look up for the closest match to the x-distance to get a rough estimate on aiming offset.

Pros: Units become more valuable as they learn, it's a lot more modern, and it makes sense to me.

Cons: Unit types with low rate of fire will not have much use of their firing table. It's also somewhat complex to implement and will cause a much larger memory footprint as the firing table grows.

For the record, I'm writing this in java/libgdx, mainly targetting the android and HTML5 platforms, but if it turns out to be decent, ports are expected. I'd love to hear other ideas for how a unit can come up with an aiming offset, as well as pros/cons. I have to pick something, and I'm not entirely convinced either of my own algorithms are right for the task.

  • 1
    \$\begingroup\$ en.wikipedia.org/wiki/… \$\endgroup\$
    – rcpinto
    Jul 19, 2016 at 18:44
  • \$\begingroup\$ For many common ballistics cases, there are closed-form solutions to calculate the firing parameters you need. Check this collection of answers for some examples. If you don't find what you need in there, consider updating your question to describe your scenario in more detail so we know what additional help you might need. \$\endgroup\$
    – DMGregory
    Jul 19, 2016 at 20:13


Browse other questions tagged .