Create a Player and Add Basic Input Movements in Unity

When creating a game, the temptation is big to immediately go for the visuals. In my first projects I fell for this trap too and believe me it is easy to spend hours on finding and creating assets. There is a better way. Before we should even think about assets, we need to understand and create the basic mechanics of our game. This is best done with placeholders.

Create your Player

Adding a 3D as a placeholder for your player

Change the game background

Change your background to solid

Change the color of your player

Adding materials to your cube.

Move your player with user input

As a first step we need to create a C# script in the asset section and attach it to our player object. Use your favorite editor or if you have installed Visual Studio with Unity, you can simply double click on the script and edit it in Visual Studio.

We first want to position our player at the start of the game. Whatever is in the Start() method will be executed once at the start of the game.

If we say movement, we say speed. Let’s create a private variable for the speed:

We then create local variables for the horizontal and vertical input whenever the WASD keys are pressed. The Input.GetAxis(“Horizontal”) will move by 1 when the A key is pressed and by -1 when then D key is pressed. The Input.GetAxis(“Vertical”) moves by 1/-1 with the W and S keys.

If you are wondering why Unity “knows” we mean the WASD keys, then have a look at some of the predefined input methods. You can find them here Edit -> Project Settings ->Input Manager.

The last step is a “transform” which actually moves our object horizontally and vertically. It looks like this:

Whenever our input method, i.e. the WASD keys are pressed we move with the speed defined in the _speed variable in real time (Time.deltaTime), which means at 1m per second.

And here we are:

Right now the player can move beyond the actual screen. And this will be the challenge in the next post.

--

--

Passionate Game Developer and Learning Expert. I love to create games and interactive experiences using Unity, Articulate, C#, JavaScript, PHP, HTML, CSS.

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
Andrea Zilio

Passionate Game Developer and Learning Expert. I love to create games and interactive experiences using Unity, Articulate, C#, JavaScript, PHP, HTML, CSS.