My 120-day journey to being a better Unity developer — Day 5
Simple player movement in Unity
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.
Next, we need to store the input values as a direction vector:
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.
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.
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.