In the last article, we learned to automate the on-screen movement of our Player GameObject. We also created a variable for our Player GameObject’s movement speed that can be adjusted from within the Inspector window in Unity. Now, still using our _speed variable, we will look at getting user input, either from a keyboard or a game controller, to control the movement of our Player GameObject.
To start, we will need to go to Unity’s Input Manager, which is located here: Edit\Project Settings\Input Manager\Axes.
Within the Input Manager, we can view the axis properties and preset control configurations for the Horizontal and Vertical movements. For instance, in the Horizontal properties, we see that the left and right keys, as well as the a and d keys, on the keyboard, will move the GameObject left and right on the screen. For the Vertical movement, we would use the up and down keys or the w and s keys on our keyboard.
It is worth mentioning that the input value that these keypresses provide is either 1 or -1.
- Pressing the d key and moving right would be X =1
- Pressing the a key and moving left would be X = -1
- Pressing the w key and moving up would be Y = 1
- Pressing the s key and moving down would be Y = -1
We also will want to know the name of the movement control to use within our code. Horizontal movement is named Horizontal and vertical movement is named Vertical.
Now it is time to access these input controls within our Player script.
Inside the Player script, the first thing we will need to do is create public variables of type float for both horizontal and vertical movements within the Update method. Then we will need to access the user input by using Input.GetAxis() and insert one of the movement names that we got from the Unity Input Manager within the parenthesis as a string, using quotation marks around the name.
Ex: float horizontalInput = Input.GetAxis(“Horizontal”);
Next, we will want to put these variables as multipliers within our movement code lines that we wrote in the last article.
Ex: transform.Translate(Vector3.right * horizontalInput * _speed * Time.deltaTime);
Now, when we save this script and go back into Unity and play our scene, we can control the movement of our Player GameObject using the up, down, left, right, or w, s, a, d keys.
Alternatively, we can clean up our code by creating one variable of type Vector3 that will contain both the horizontalInput and verticalInput variables inside of a new Vector3, replacing the X and Y axis values.
Then we would use the Vector3 variable named inputDirection within only one line of code as opposed to two lines, multiplying it by our _speed variable and Time.deltaTime, achieving the same results.