Controlling the Player with the Keyboard
In order to be able to move our Player horizontally or vertically with our keyboard using the Left arrow, Right arrow, “a” and “d” keys for horizontal movement or the Up arrow, Down arrow, “w” and “s” keys for vertical movement, we must access Unity’s Horizontal and Vertical Axes.
If you would like to see these access points, in Unity, go to Edit > Project Settings > Input Manager > Axes
By selecting the Horizontal Axis, we can see what is mapped to it.
We can see that the Left arrow, Right arrow, “a” and “d” keys will move an object left or right.
The Up arrow, Down arrow, “w” and “s” keys will move an object up and down.
So, what happens in Unity when we actually select one of these keys? Well, the Left arrow, Down arrow and the “a” and “s” keys will return a -1 to Unity.
The Right arrow, Up arrow, “d” and “w” keys return a 1.
These values can be stored in a variable and used to determine the direction of the object.
These variables will store a -1 when the object moves left or down, or a 1 if it moves up or to the right.
With this information, we can now add it to our player movement:
How this works is, when horizontalInput is -1, then the X value of the Vector3 will be negative thus making the object move left. If it is a 1, then the X coordinate is positive making the object move to the right.
The same thing can be done with the verticalInput to control the up and down movements of the object.
With this code, we can now control the movement of the object using the keyboard.