Unity Game Dev : Input manager

Time to move our Player!
To do that, we need to use the Input manager.
This can be find under Edit, Project Setting, Input Manager

From here, click the little arrow near “Axes”

Unity, by default, have 18 different axes to map user input, and we can also add on our own.

What interests us at the moment are the horizontal and vertical axes.
If we open “horizontal”, we can see there are some key predefined, and the alternatives.

left and right arrow are default, “a” and “d” are the alternatives

Now, we see from image above that “horizontal” axis can move Player with “a” and “d” to left and right, but how?

First of all, we need a public variable to see what happen.
So we create a variable of type float

And we assign that variable to the Input we need, horizont axis

When we open parenthesis, it ask us a string to pass, and we pass the name of the axis, Horizontal.

Back to Unity and see what happen.

Player obvliously move because we have this in the Update method

Player obviously move because we have this line of code in the Update method

What we interest to us is this :

The variable “horizontalInput”” change, when we press “a” it go to -1, when press “d” it go to 1, if don’t press nothing, stays at 0.

Now we can delete the public variable and use it directly in the transform.Translate method
Delete this

and change this to that

We change the SCOPE of variable

Now, use this variable in the Translate method

Simply CTRL+C on variable and and CTRL+V

Save, back to Unity and press Play

If we use “a” or “d”, Player move left or right.
It works even with arrow left and arrow right.

To move Player vertically, is the same thing, simply we manipulate the vertical axis.
First, we create the float value variable for verticalInput Then, to move vertically, use another Translate with Vector3.up to move Player up and down

That’s how manipulate the Input to move Player.

ADVANCED TIP: There is a process called refactoring, and it means taking the code we wrote and making it READABLE, and possibly without repetition. Readable because we will often not work alone, so our code must be clear and understandable. Without repetitions especially for a matter of performance: later in our journey, we will find that we have to be very careful about what we put into the update method. Every single thing we write needs space and memory management is INCREDIBLY IMPORTANT, even if Unity helps us with “Garbage Collector”.

I just wanted to mention it because it is a very important part, even if for now we can not think about it!

So, in the next session, let’s rewrite the code in a better way, because, even if it works, it’s not very good!

See you in the next article!