My 120-day journey to being a better Unity developer — Day 5

Simple player movement in Unity

Jean-Noel Seneque
3 min readMay 2, 2021
Using WASD keys or Game Controller

Objective: Make the cube move around the screen by pressing the WASD keys or a game controller.

Let’s start by getting the direction of where we want to move the cube. To do this, we need to capture the player’s input for both the horizontal and vertical directions.

Capturing the keys pressed

Next, we need to store the input values as a direction vector:

Creating the direction vector using the input values

Now, every game object at its core has a transform position. There are a number of ways to move a game object and in this example, we will explore the Transform.Translate method:

Let’s put in the direction vector and see what happens:

Well, our cube did move. What happened here is the inputs pass values close to 1 which meant 1 unit or 1 meter per frame and with the game running at approximately 60 frames for second…zoom! What we really want is to move the cube 1 unit per second. We can use Time.deltaTime that provides the time difference from the current frame to the previous frame which works out how far to move the cube in that small time.

We have better control but too slow

This is where we add a movement speed variable. We may not know the right speed but we can create a way to test this out during runtime.

Add a speed variable

On the game object where the PlayerMovement script is on, we now have the Move Speed property available in the Inspector that we may adjust to get the right feel for the movement we are looking for.

In the Inspector tab

Final Result and code:

Move Speed at 5
PlayerMovement script

--

--

Jean-Noel Seneque

A Data & Analytics Consultant who is expanding into developing experiences in XR, Enterprise and Gaming space using Unity www.jeannoelseneque.com