In the previous article we used a speed variable to give our sprite a “speed”.
In that case, multiplying the Vector by a value, its DIRECTION will always remain the same, but its LENGTH will change (MAGNITUDE).
If our Vector were (1f, 1f), multiplying it by a number greater than itself will become longer, while for a smaller value, for example 0.5f, it will become shorter.
If the multiplier is NEGATIVE, its DIRECTION will also change, which will be rotated 180 °
Vector2 (1, 1) * 0.5f = Vector2 (0.5f, 0.5f)
Vector2 (1, 1) * -0.5f = Vector2 (-0.5f, -0.5f)
Everything we have seen before can be summarized as follows:
transform.position += new Vector2 (0.5f, 0.5f) * _speed;
And in the Update our position will update at each frame with the addition of our Vector.
Ok, after seeing the Vectors in action via the keybinding, we will try in the code to apply these theories to make our sprite move from one point to another automatically.
Calculating the DISTANCE between two points, in Game Programming, will be something that will happen many many times, especially if we are programming an AI for the management of enemies for example.
In our scene I added a circle, and I called it Enemy.
And I renamed our sprite Player.
Now, what we want is that our Player automatically moves towards the Enemy.
We have a first point
P1 (x1, y1) and a second point P2 (x2, y2).
Based on this, how do we calculate the distance, the Vector V?
At a very basic mathematical level, we can say that knowing the point P1 and the vector V, it will be very easy to calculate the point P2
P2 = P1 + V
Very simple, adding Point1 to the Vector gives Point2
Knowing this, inverting the formula to calculate the Vector V knowing the two points P1 and P2 is even easier
V = P2 - P1
So in Unity we apply exactly this formula to calculate our Vector
Let’s recreate our script from scratch:
a variable for the speed otherwise our Player will immediately find itself on our Enemy, and a reference always to the Enemy
Now, first we calculate the Vector V.
By applying the formula, we subtract our position from the enemy’s position to get the distance.
To move, we need to add the Vector to our position and multiply it for speed
Remember to drop the Enemy in the Player’s inspector
If we make a test
And it works exactly how we want.
Obviously we can move the Enemy anywhere on the “map”, the result will not change, (except for the direction and length of the Vector) and our Player will start from its position and arrive at the enemy’s position.
By continuing to move the enemy at runtime, our Player will continue to move to try to reach it.