Vector3.Distance error

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.

Vector3.Distance never returns the wrong value and is not affected by scale; here’s the code from UnityEngine.dll:

public static float Distance (Vector3 a, Vector3 b)
{
	Vector3 vector = new Vector3 (a.x - b.x, a.y - b.y, a.z - b.z);
	return Mathf.Sqrt (vector.x * vector.x + vector.y * vector.y + vector.z * vector.z);
}

Log the actual cannon and target positions so you can see what they actually are, rather than just assuming. You can bet that none of the built-in math functions will ever return “wrong” results, so it’s not productive to go down that path.

Try something like:

var CannonPos = transform.localPosition;
var TargetPos = Target.transform.localposition;
var distance = Vector3.Distance(TargetPos,CannonPos);
Debug.Log(distance);

The distance shouldn’t be wrong, so perhaps your Vector3s aren’t in the places you intend them to be in.

On the side note, here are some tips while programming:

  1. If you’re using JS, explicitly declare your variables or it could get a lot laggier. For example, explicitly state that your dist var is a float, that your positions are Vector3s/Transforms, etc.

  2. Vector3.Distance isn’t great. I’d suggest just manually calculating the magnitude by doing (Vector1 - Vector2).magnitude