# Problem with auto-aiming precision

So I have this turret shooting bullets at a directly passing cube. However preaimed bullets seems to miss the cube if it's not somewhat sideways.

http://img221.imageshack.us/img221/5162/29559547.jpg (Purple arrow = the moving direction of cube, Red line = predicted position, Blue line = line to the cube)

Preaiming code looks like this:

``````        //Get distance to enemy
distanceToEnemy = Vector3.Distance(transform.position, enemy.position);

//Calculate the time it takes for a bullet to reach the enemy
timeToTarget = (distanceToEnemy / 30); //30 is bullet speed

//Calculate the distance amount needed to add in front of the enemy
preaim = (timeToTarget * 10); //10 is the enemy's moving speed

//Add the previously calculated distance in front of the enemy
predictedPosition = (enemy.position + enemy.TransformDirection(Vector3.forward * preaim));

``````

I'm not that good with physics so what am I doing wrong with the calculations?

The calculation you are doing is not 100% correct. Under some circumstances it might look correct (e.g. target is relatively big, or speed is slow), but the problem is you are calculating how long the bullet will travel to the current target position. Then you calculate the position that the target will be at after that time and use that as a target position. However, the time the bullet needs to travel to that new position is probably not the same as the travel time to the original position, so chances are that your bullet will miss the cube anyway.

Leading a target is a bit more complex than this. A good description can be found here:

http://howlingmoonsoftware.com/wordpress/?p=358

If you want to guarantee the bullets hit the target, why not use LookAt() on the projectiles themselves once you instantiate them?

I'd say the example code had not that clearly named variables but I got it translated anyway.

In order to get it working I had to apply rigidbody for both my enemy and the turret to get the ".velocity". Like this:

``````    //before
enemy.position += enemy.forward * speed * Time.deltaTime;

``````

So one additional question. Is rigibody's velocity frame dependent