Math in Unity : Vectors (Part II)

Matteo Lo Piccolo
3 min readOct 16, 2021

Now let’s do a couple of practical examples on how to move our sprite.
I created a simple script called SpriteMove

For example, if we had a Vector 0.5f, 0.5f, 0

and we want to use it as a direction, how can we do?

First of all, we need a reference to our position.

Just to test, in the Update we will add our position to the Vector, and update our position.

or we can use this

Then, we update our position by assigning transform.position to myPos

Play it

Obviously, being in the Update (), our sprite will start very valid in the direction indicated by the Vector (0.5f, 0.5f)

To better understand this mechanism,
we will use the WASD keys to move in any direction, always using our Vector as the direction.

As we can see in the script, the logic is very simple.
The _direction Vector is obviously formed by an X and a Y.

What we can do when we have a Vector as a direction is to use it “all”, that is to have the complete direction in 2D or 3D, so X and Y or X, Y and Z.

Or use just one of the 2 (or 3) axes and add it to our X, Y or Z position.

I also created a _speed variable and decreased
Vector2 value to 0.1f, 0.1f.
Again, just to test and have movement speed, nothing particularly complex.

So now we have 0.3f for X and Y.

This is my script to move the sprite.

If we test it

We can move the sprite in all 4 direction

NOTE : Obviously there are better ways to manage the movement, but to better understand the concept of Vector I wanted to use a very very simple system to see the two vectors added together and get a direction.

This article may seem a little more “basic” than all the others, but Vectors can be very complex in the long run.

Starting from here we will go deeper and deeper, we will talk about the normalization of the Vectors, what is the Cross product, the Dot Product, up to the rotations.
After that we will try to deepen by touching on topics such as intersections and matrices.

I don’t consider myself an expert, so I hope these articles are useful for you and me at the same time.

See you next article!

--

--

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!