In my AI targeting code (for enemy gun turrets, etc), I’ve been using Vector3.Distance to calculate the distance to the enemy vessel. After running into persistent problems, I finally used Debug.Log to print out the distance that Vector3.Distance was calculating, and the distance is always way off - e.g. over 4000 for a test target which is only 1000 straight in front of the gun, with only one coordinate which has a different value (since it’s straight ahead), and parented to the same ship so it can’t get farther away than its starting distance. Here’s my code which is attached to the gun object (in Unityscript):
var CannonPosition = transform.position;
var TargetPos = Target.transform.position;
var dist = Vector3.Distance(TargetPos, CannonPosition);
As you can see, my code is very simple, so it’s hard to see what could be wrong with it unless Vector3.Distance is returning the wrong value. And the variable “Target” is defined in the inspector by dragging the target’s gameobject to that variable, so there isn’t much that could go wrong with that either. I’ve confirmed that the defined target is the correct one.
My only theory is that if either of the gameobjects for the gun or the target are scaled (as these ones are), then maybe Unity changes the distance calculations accordingly? I don’t know what else could be the source of the problem.