Math in Unity : Vectors (Part IV)

In this article we will slightly update the previous code.
We have seen that by calculating the Vector v and adding it to our position, our sprite (in the Update ()), moves at a constant speed and stops exactly above the circle.
Everything good.
Now, let’s do a little test to see how Vectors work.

First of all, I change my local variable v to GLOBAL.

And of course we change it here too

As you can see I put the calculation of Vector v in Start ()

Since we have done this step, leaving this piece of code the same in the Update we will have an obvious problem:

in Start () we calculate the Vector, but in Update () it will be constantly recalculated and added, without ever stopping.

To fix this small inconvenience, we will use one of the most used methods: VECTOR3.DISTANCE ()

Here is the reference to the manual :
https://docs.unity3d.com/ScriptReference/Vector3.Distance.html

First, we will create a float to manage the stop distance

So we’re going to use it like this.
in the Update you will need an If statement

We will delete the true, and use this string of code:

Don’t worry about the mistake, a little bit is still missing.
What happens inside the brackets is simple: Vector3.Distance () takes 2 parameters, Vector a and Vector b.
Automatically, with this method, Unity calculates the distance between the two points

So if we compare the distance between the two vectors with our stoppingDistance

what we get is very intuitive: if the distance between our two Vectors is greater than the stoppingDistance, then keep moving, otherwise stop

Now the sprite stops above the circle again

Before closing, we will do another very interesting test.
If we duplicate our sprite and put it here

If we press Play

Both sprites arrive at exactly the same time on the circle, although the distance of one is less than the other

This can be explained by a simple calculation:
obviously the farthest Vector is longer, and when we multiply it by the speed, it will move more units than the other.

We simplify:

if Vector A is 0.1f, 0.1f long
and Vector B is 0.3f, 0.3f long

if the speed was 2f,

Vector a will be 0.2f, 0.2f
Vector B will be 0.6f, 0.6f

this explains why they both arrive at the same time.

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!