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

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

--

--

--

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

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Update Subbing

#WirVsVirus Hackathon — S.W.A.G.

This week in #Scala (Mar 1, 2021)

Cloud Custodian Policies for CIS Microsoft Azure Foundations Benchmark (Part 3)

How to get started as a Machine Learning Engineer.

Running your own Bitcoin node.

How to organize teams to get the best out of them

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Jean-Noel Seneque

Jean-Noel Seneque

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

More from Medium

3rd Person Follow Virtual Camera Explained in Unity’s Cinemachine

Racing Car Game # Day 6— New Unity Input System

Application.Quit — Exiting the Application

Unity Interface Layout