Simple Player Movement in Unity

All objects in Unity have a transform component. The transform component dictates where the object is oriented in the scene.

The three key functions of the transform are the position, the rotation and the scale. These all function on the X, Y, and Z axes.

Within our scripts, the transform and it’s functions can be accessed with ‘transform.position’ ‘transform.rotation’ and ‘transform.scale’

To simply assign the position of the attached object, the transform can be assigned a new position — this is where Vectors come in to play. Vectors allow us to assign values in the 3D space, for example, moving the position of our object on all 3 axes. Written out in code looks something like this:

But how do we make it move? The transform has a function called Translate which allows us to apply a change in direction. To do so we use it in the Update method, for example.

Try it! This results in your object going zoomies off the side of the screen. This is because it is being moved 1 unit to the right every frame, which is generally 60 units per second! To fix this, we need to multiply our Vector 3 by Time.deltaTime allowing us to move 1 unit per second rather than relying on our framerate.

To alter the speed, add in a multiplier! My example below results in my player moving 5 units to the right every second.

Let’s add some control. To do so, we need some input. Unity has a built in Input Manager that comes preassigned with a standard control scheme. The two basic movements we want are along the horizontal and vertical axes. To access these inputs in Unity we can establish float variables for each and use the following code:

Now when we hold down our arrow keys or ‘WASD’ we establish an input for each between -1 and 1, with 0 being no movement. Now, we could add these new variables as a multiplier for our previous code, but that seem’s a bit messy. Instead, we can create a new Vector3 to house our input values.

From here, our transform.Translate function can be adapted to:

With that, we have an object that can now move around the screen with our input!