Math in Unity : Vectors (Part VII)

Now let’s move on to Distance ()
Inside we pass two vectors, and calculate the distance.
The formula to be applied is the one seen in the last article, therefore

we will need the sum of

then, the square root of the result

Let’s put it into practice!

First we calculate the difference between all points.

We will now need the square root of the difference.
Again, we will use MathF, specifically the Sqrt () method

Another very useful method in these calculations.
Incredibly simple, we pass in a value and automatically the square root will be calculated.

And we return the result.

We used this order for a reason:
to calculate the Distance() we needed Pow(),
to calculate the Normalize() we needed the Distance()

How?

vector.x / = lengthvector.y / = lengthvector.z / = length

Now, to calculate the LENGTH, we have already the Distance() method.

So we write something like this :

We now need two Vectors to calculate the length right?

Now, we know that a Vector that starts from a point 0 and has coordinates, will have its point of origin in 0, 0, 0 and its end point in its coordinates, okay?
And wherever it is in space, its length will ALWAYS be the same.

If vector A is (1, 1, 1)
It can be found EVERYWHERE, but its LENGTH WILL ALWAYS BE (1, 1, 1)

Whether it starts from (0, 0, 0) or from (2, 2, 2), its length remains the same.

So in this case we can safely pass a 0 point as the origin, so Vector3.zero
While the other parameter will obviously be our Vector.
In fact the distance between 0, 0, 0 and the “vector” that we will pass will be exactly the length of the Vector we need to calculate the Normalize.

Now that we have the distance, we simply need to use it to divide each point on the vector in this way

And we return the vector.

To test the result, we still need to make some minor changes.

In the next article we will finish this work.
Feel absolutely free to test and do experiments!

Always in love with programming, even if late (I'm already 39 years old) I decided to follow my dream! We will see how far my passion will take me!

More from Matteo Lo Piccolo

Always in love with programming, even if late (I'm already 39 years old) I decided to follow my dream! We will see how far my passion will take me!