So I spent today tackling again what I couldn’t do a month or two ago. Predictive Aiming! It was time I solved this problem if I wanted to move forward even more with my progress on the game. And I FINALLY figured it out! It’s actually not that complicated. I’ve seen like 1 or 2 tutorials on this subject but they were either not exactly what I was looking for or it was made overly complicated to the point where I couldn’t understand what was going on.
So normally, when the turret shoots a “moving” target, if that target is far away.. chances are that the bullets will miss unless it’s going at lightspeed. That’s where I had to figure out a way to predict where this moving target was going to move next and for the turret to aim at that position.
To solve this problem, I made some variables that tracked where I believe the target will move to in the next second. Since the target has a move speed of 2 via the Rigidbody, it’s moving 2 tiles in 1 second. So say the angle of this Target was 45 degrees. So the sides would be 1.414 in length while the hypothenuse is 2 since that is 2 tiles diagonally.
What I want from the turret is to not shoot where the Target currently is, but where the target will be that next second where it has moved 2 tiles. So I draw a triangle from the current turret location and the future position of where the target will be at. Use the Pythagorean theorem and we’ll get the hypothenuse from the turret to the Target’s future position.
Now I want to know the angle in which my turret will shoot at to hit the target’s future position. Since I know the opposite and adjacent sides length, I can now get the angle of the turret and the bullet that comes out of it. Still, even if I know the angle of where to shoot… this angle is basically saying that in 1 second time, it will collide with the target’s future position. But the Hypothenuse is say… 7. So if the Bullet is moving at 10 tiles per sec, the Turret doesn’t need that full 1 second to collide. it will actually shoot too soon, so I will need to adjust the angle some more.
I take the distance which is the hypothenuse and divide that by the speed of the bullet and multiply that with the difference between the current angle and the angle that will hit the target’s future position so that I get the angle of where it would be after .7 seconds. So the new angle will be more then the current position and less than where angle would be at if it shot too soon.
And that’s basically it! It works out as you can see from the Clip. So, I’ll just need to use this same concept for my Interceptors when hitting incoming Missiles. Cheers!