Day 6: Player Input! We can move them now!
Yesterday we talked about moving the character with transform.Translate(). It gets boring because the player has no way of manipulating the character. Today we will discuss adding input that will allow the Player to control the character.
Unity has an input system that makes taking player input a lot easier. We will start by going to your project and going to Edit and Project Settings.
A new window will pop up and on the left hand side you can find Input Manager, that is where we are going.
With Unit’s Input Manager, there are predefined axes. Each axes has keys and alternate keys to get from the player to move on that axes.
With horizontal, the system is looking for input from the player on the left and right arrow keys as well as ‘a’ and ‘d’ keys. The horizontal will run on the x-axes and vertical will be y-axes or z-axes depending on how you hook it up in game. Now to add input to the code.
In you code editor, you are wanting to look for those input. You want to add a float variable to collect the data from the input. Reason for a float is the input will be between -1 and 1. If you hit left it’ll move from 0 to -1 and right 0 to 1. Since it’s doing decimals we need a float.
Since we now are holding the data for the input, lets add them to a vector3 so we can move. Since we are using the input manager, to add the Horizontal Input, we start by creating our variable, and assign it the Input.GetAxis(“Horizontal”). Input is the class we need, GetAxis is a function that takes in a string. The string you input will need to be a name from the input manager and spelled correctly.
There are two ways of doing this, I will show how I like to do it by creating a local vector3 variable and input that variable input transform.translate().
I add the local variable to make it easier to edit later on if I need to. Just looks cleaner to me. You can just add the new vector3 input the transform.Translate() if you want.
Now in your project you can now move the character at your will!