Movement is everywhere around us. Some things move with the wind, others with the waves and some things can even move themselves.
But how do you make things move within Unity you might ask? Simple! we use the transform component to move it around, now let's take a quick look at some ways we can achieve this.
If we are talking about movement in Unity we are essentially talking about manipulating the “Transform” component.
So what is this component? You can look at it as a GPS tracker that is linked to your object, it tells you the Position within the world space or relevant to the Parent object(more on that later), the Rotation and the Scale(size) in a format called XYZ Axis.
Move the object the values change, Change the values the object moves.
With this knowledge how do we get it to move? We use Translate.
Moving things around in unity is done with a command called “Translate” (move from one place or condition to another).
To make an object jump up and down we are only manipulating the Y values on the Position property.
Movement with C#
Now let us achieve the same thing using some code.
To create a new script and link it to an object right-click on your Assets folder then Create -> C# Script and give it a name like “Move”. Now just drag the script onto your object so it becomes a component of this object.
First we need to access the transform component, if the script is attached to the object we are trying to move we can access it directly by typing “transform” to access the component and “Translate” to tell it to move.
But move where and how? For this we need to tell it where to move to in a format called Vector3 in this case we want it to move up so we use “Vector3.up” This will add 1 to the Y value of the Position property. If we now put this into the void Update and press play you will see your object take off like a rocket!
We might want a bit more control over the speed so let’s take a look at how to do this.
Update is dependent on your hardware but runs around 60x per second Time.time can be thought of as realtime
So by multiplying the vector with this value we get more stable movement in this case +1 per second on the Y.
And voila! your object now moves smoothly across the screen.
Next time we will go over how to control the speed using variables and how to use player input to actually move the object yourself.
But for now, thank you for reading and happy coding!