# Calculate distance between two objects

How can i calculate the distance between two objects in unity using javascript?

``````var distance = Vector3.Distance(object1.transform.position, object2.transform.position);

``````

Look at the reference for Vector3.sqrMagnitude (with example).

There is also Vector3.magnitude...

but what is the difference between using Vector3.Distance(a,b) and Vector3.magnitude(a-b)? Does one compute faster than the other?

A more mathematical approach, you could use the Pythagorean Theorem and calculate the hypotenuse using the right triangle with the grid units in unity.
So, the square root of (delta)X^2 + (delta)Z^2 = flatdistance (this is a var)
and then…
square root of flatdistance^2 + (delta)Y^2 = distance between the two points

My suggestion is to avoid taking the square root of anything.

I would do this buy finding the distance of characters x and y position from target and squaring each one and add them together.

(Yc - Ye)^2 + (Xc - Xe)^2 = D^2 , Where Xc and Yc are your characters position. amd Ye, Xe is the enemies and/or targets position.

for comparing it if it is in range, use range of whatever R, display it as R, but internally it should be stored as R^2 to compare to D^2. Thus avoiding any complicated math.

if you are using 3d graph you need to ad deltaZ^2 to D^2 as well (delataZ = Zc - Ze)

Why do I suggest not using the square root, first. you can use the distance squared just as easily as the you could use the actual distance and taking the square root of a number is slow… I mean it only takes around O(log n) (or better depending on what method is used) but to do better you need complicated math which might not actually make it any faster (depending on the processor being used)
where as keeping the distance as itself squared gets rid of an unnecessary object and takes O(1) time i have written a blog related to it check the link