Simple Player Movement in Unity

In this quick guide I will show you how to setup simple player movement like in a 2D/2.5D Space Shooter type game where you only move on the x and y axes.

To get a scene looking like the gif above …

First create a cube in Unity and add a material for color, change the Clear Flags setting on the main camera to a solid color, mine is black.

Now create a script named Player and add it to your cube.

We’ll be using the legacy input system.(I will write another article on using the new input system in the future)

Under Project Settings/ Input Manager you will see all of the different inputs and their names.

We’ll only be using the Horizontal and Vertical inputs to move the player on the x and y axis which are mapped to the arrows and wasd keys.

To move the cube we will use transform.Translate in our Update method

transform.Translate needs a Vector3 passed in to know which way to move.

For example to move right or left (horizontal) on the x axis we will use Vector3.right which is exactly the same as typing new Vector3(1, 0, 0)

For moving up and down (Vertical) on the y axis we will use Vector3.up which is exactly the same as typing new Vector3(0, 1, 0)

We need also need a speed variable, I have mine set to private with a [SerializeField] attribute so that it can be modified in the inspector.

We also need to multiply it all by Time.deltaTime so that is moves in real time.

Start by creating a local float variable in the Update method that references the Horizontal and Vertical inputs by their names in the Input Manager using Input.GetAxis(“Insert exact name from input manager here”);

float horizontalInput = Input.GetAxis(“Horizontal”);

float verticalInput = Input.GetAxis(“Vertical”);

Now add and multiply your Vector3, horizontal or vertical input , speed variable and Time.deltaTime to your transform.Translate

Go ahead and test in Unity and it should all be working.

To further optimize we can combine the two inputs into one line as the inputs are being multiplied by 1 in the Vector3.right and Vector3.up so you can just put them into a new Vector3 like this…

Vector3 direction = new Vector3(horizontalInput, verticalInput, 0);

transform.Translate(direction * _speed * Time.deltaTime);

Instead of creating a new Vector3 twice every frame it will now only do it once.

Unity Developer/C# Programmer for VR, 2d,3d Games and other Immersive Interactive Experiences