There are a couple old projects I recently realized aren’t visible anymore (because they were using old player technologies) so I decided to dust them off and do WebGL builds of them. I’ll talk about the other next month, but in this blog post I just want to focus on one, the demo of an algorithm I devised for aiming at a moving target. The interactive demo is on my space at itch.io:
Decades ago I had programmed this as a little cheat/mod for an open-source Missile Command style game, years later implemented it in AS3 to make a Flash demo, and just now decided to port it to C# for use in Unity.
Unlike how other people generally approach this problem, I did it as a recursive feedback loop. There’s a rough estimate that gets calculated, then that result is fed back into the next iteration of the calculation, resulting in a slightly more accurate estimate, and repeat a few times until the estimate is within a pixel of accuracy. Here’s the demo on github if you want to inspect the code.
On a QA page where I discuss the algorithm (plus link to the original Flash demo) a commenter there pointed out a big advantage of my approach (versus how other people were doing it): even if there is no exact solution, the shooter will still fire roughly at the target.
Another useful thing about this approach (although I don’t do it in this demo) is that the calculation can be spread over multiple frames. Or rather, each iteration could be done on separate frames, with the full loop happening over time. Here it’s such a simple calculation that spreading it out would be pointless, but I can see that being an advantage if there were tons of AI shooters or less powerful hardware or something.
One thought on “Algorithm for Aiming at a Moving Target”