(1, 0, 0) WASD

Shwetaketu Dighe
3 min readMay 7, 2021

--

Let’s look at some basic movement in Unity!

Usually, one of the most crucial mechanic in most games — Movement, is something we spend most our time on when we play games. Let’s create a simple system to get input from the player in any of our four primary cardinal directions and relay that information to our player character so that it can move in any of the eight directions. Let’s get started.

To begin with, take a look at the Transform component. Every game object in Unity has a transform component, this defines the position, rotation and scale of that particular game object. Take a look at Unity’s architecture here;

notice this hierarchy in Unity

Foremost, let’s look at getting a prompt from the player. Using the Input.GetAxis method the default “Horizontal” and “Vertical” axes will give us values ranging from -1 to 1 when any of our arrow keys, WASD or left joystick inputs are prompted by the player. Here, we make two floats; ‘horizontalInput’ and ‘verticalInput’ to save these values.

-1 being the max value for left and down while 1 being the max value for right and up.

The position property of transform gives us the world space position of our game object in a Vector3 and like any Vector3 it further has x, y and z properties within it. Manipulating the x value will move our player horizontally whereas changing the y value will move our player vertically. Since we are covering 2D movement in this article, the z is supposed to be unchanged or 0.

change x to move horizontally and y to move vertically

To change the x and y values of our game object, lets look at an important method of the transform component; Translate. This method moves the transform in the given direction by a specified distance. We can use the transform.Translate and pass in a Vector3 to get our character moving!

From this point on we can either create a new Vector3 to store horizontalInput and verticalInput as the x and y value, like so:

Or we can directly multiply the floats with Vector3.right for horizontal movement and Vector3.up for vertical movement.

In addition to the Vector3, we need a float variable for the movement speed and last but not the least, we multiply it off Time.deltaTime to make it framerate independent.

So that’s how we get our character moving. Cheers!

--

--