# Enemy AI prediction aiming isn't working as expected

I have used three, different, clever algorithms to use the power of math to predict exactly where to aim to hit a moving target. The results are buggy and jittery, both jumping around randomly and not particularly accurate otherwise.

I’m going to try to list everything that may be relevant, because I cannot seem to figure this out on my own.

These algorithms all require getting a few variables. Target position and velocity, gun position and velocity, projectile scalar.

• Scalar (projectile speed float) is easy, so I probably didn’t mess this one up. It’s just the float speed divided by the fixed update time. So my 500f bullet speed / 0.02 fixed delta time = 10f. Bullet firing code looks like instBulletRigidBody.AddForce(forward * 500f);
• Target position I must have right, because if I stand still, they hit the target player dead center.
• Target velocity: no ridigbody to steal velocity from, so I just calculate it by recording the last position (previous fixed update’s current position) and subtracting that from the current position, divided by delta time like so: targVel = (targetCurrentPos - targetLastPos) / Time.fixedDeltaTime;
• Gun position: I grab the transform for the emitter on Start, Gizmos.DrawSphere(myPos, 0.05f); shows it exactly where it should be.
• Gun velocity: Calculated just like target velocity: myVel = (myPos - myLastPos) / Time.fixedDeltaTime; Though, the enemy doesn’t even move except to rotate, so whatever.

Finally, I use the resulting V3 from the above algorithms (the direction to aim) and rotate the enemy/gun with transform.LookAt(aimAt); before firing (or every fixedupdate), and the result is the atrocious gif above. If the player doesn’t move at all, the accuracy never even peaks 50%. Something is horribly wrong.

Doubt it’s relevant, but this is how simply my player is moving in Update:

``````Vector3 move = new Vector3(2f * Time.deltaTime, 0, 0);

transform.Translate(move);
``````

As a note I tried the “dumb” way that doesn’t take into account how long a projectile will take to reach the target’s new position, and it’s actually more accurate than my attempts at doing it the right way. At least, up until the target is moving away from the enemy.

If you have any ideas what I should look into, please let me know. I’ve wasted over ten hours on this.

Dear fucking god I’m stupid.

Doubt it’s relevant, but this is how simply my player is moving in Update:

moving in Update

Update

I am quite upset with myself. I have literally lost 15+ hours trying everything and it’s because I put the player movement in Update instead of FixedUpdate. I’m going to go cry now.

[SOLVED]