Read keyboard input to control 2D character movement

Tutorial

·

Beginner

·

+10XP

·

40 mins

·

(3066)

Unity Technologies

Read keyboard input to control 2D character movement

The player character can move, but at the moment it does so whenever you test the game. Now you need to configure it to move only when the player provides specific input.

By the end of this tutorial, you’ll be able to do the following:

  • Read the current state of a player input device (keyboard).
  • Apply horizontal and vertical movement to a GameObject in response to keyboard input.

1. Overview

Player input is a critical part of most games, whatever the players actually control. In 2D Beginner: Adventure Game, the player will control character movement around the full environment that you create using an input device. Unity has a package that can help you do this: the Input System.

By the end of this tutorial, you’ll be able to do the following:

  • Read the current state of a player input device (keyboard).
  • Apply horizontal and vertical movement to a GameObject in response to keyboard input.

Working on your own project?

This tutorial is part of Beginner 2D: Adventure Game, but you might find it useful if you want to create a 2D character controller that works using Unity’s Input System package. For further guidance on using the package, refer to the Input System package documentation.

Important: If you are working in your own 2D Unity project, make sure that you have installed the Input System package before you continue with this tutorial.

For the purposes of this tutorial, we chose to use the Ruby’s Adventure asset set, and the file paths used in instructions will reflect this. If you chose another asset set, the file names will be the same, but in your corresponding theme folder.

2. The Input System package and your game

You’re going to use Unity’s Input System package to allow your player to control the movement of their character in your game. The Input System is a flexible and relatively new system that you can use to allow players to control content in Unity with any kind of input device.

For this game, you’re going to focus on a keyboard as the input device, but as you become more experienced you will be able to create more flexible input configurations and allow players to remap the controls that they use to play your game.

How does the Input System package work?

The Input System enables you to define particular Input Actions and bind them to controls on an input device. An Input Action is something that the player can do in the game; running, jumping, or interacting with an object, for example. When the player interacts with a control that is bound to a particular Input Action in the correct way, that action will occur in the game.

For example, you might decide that the player character should jump whenever the player interacts with a particular control (a key on a keyboard, for example). To do this, you would need to create an Input Action for jumping, and then bind it to your chosen control.

Input for the 2D adventure game

In these tutorials, we’re going to guide you through setting up your 2D adventure game for keyboard input by default. However, you can also bind alternative inputs to the Input Actions that you define — you don’t need to write additional code to make this work for your game.

The scope of this course

We’ve decided to guide you through a very basic approach to working with player input for 2D Beginner: Adventure Game. There are additional tools in the Input System that you can use to work with inputs in more efficient ways, including Input Action Assets and the Player Input component. However, the workflows for these tools require more scripting than the beginner approach that we have chosen for this course.

If you are a more experienced developer, you can find more information about these tools and workflows in the Input System package documentation.

3. Read input from a keyboard

At the moment, the PlayerController script that you’ve written adds 0.1 to the PlayerCharacter GameObject’s horizontal position every frame of the game. However, you need to change this script so that PlayerCharacter responds to inputs from the arrow keys on the keyboard instead.

Let’s start by reading input directly from the player’s keyboard. To update the PlayerController script, follow these instructions:

1. Open the PlayerController script in your IDE.

Note: Remember you can find the PlayerController script in the Project window, in the Scripts folder.

2. At the top of the script, beneath the existing namespaces declarations and before the class declaration, add the following instruction:

using UnityEngine.InputSystem;

This instruction tells the computer that the script needs to use the Input System package features and functionality.

3. Go to the Update function and add the following instruction on a new line at the top of the code block:

float horizontal = 0.0f;

This instruction declares a new float variable called horizontal and sets its value to 0.0. Remember, the semicolon at the end of the instruction is vital; it tells the computer when one instruction ends and the next one begins

Important: Make sure that you add the instruction inside the Update function’s braces.

5. Add the following code directly below the declaration of the horizontal variable:

if (Keyboard.current.leftArrowKey.isPressed)
{

horizontal = -1.0f;

}

Take a moment to consider what you learned when you first set up this script before you read on. What do you think this instruction is telling the computer to do?

Here’s an explanation of your change:

  • This instruction begins with if. If statements are logical conditions that tell the computer what to do if a particular condition has been fulfilled.
  • The instruction uses the dot operator to check if the Left arrow key on the keyboard is currently pressed.
  • If the Left arrow key is being pressed when the instruction is executed, the variable that you just created is set to -1.0 (movement left along the x-axis).

6. Below this, add the following code:

else if (Keyboard.current.rightArrowKey.isPressed)
{

horizontal = 1.0f;

}

Based on the previous conditional statement you added, what do you think this one does?

Here’s an explanation of your change:

  • This code begins with else if, a conditional statement that is run if the condition for the first if statement has not been met.
  • If the Right arrow key is being pressed when this instruction is executed, the variable that you just created is set to 1.0 (movement right along the x-axis).
  • If neither of the conditions are met (that is, if neither the left nor the Right arrow key is being pressed) then the variable will remain set to 0.0 and the player character will remain stationary.

7. Leave one line clear and add the following instruction directly below the conditional statement:

Debug.Log(horizontal);

This instruction prints the value of your float variable to the Console window in the Unity Editor.

4. Apply horizontal movement to the player character

Now that you have set up your script to read keyboard inputs for horizontal movement, follow these instructions to apply that movement to the player character:

1. Underneath the code you have just added, find the position.x = position.x + 0.1f line and update the instruction as follows:

position.x = position.x + 0.1f * horizontal;

This instruction now sets the Position X-value to the current position plus 0.1 multiplied by the value of the variable horizontal. This will set the variable’s value to the following:

  • Left arrow key pressed: current position + (0.1 * -1)
  • Right arrow key pressed: current position + (0.1 * 1)
  • No key pressed: current position + (0.1 * 0)

Note: Using the WASD keys will not move the player character, as the added code only applies to the arrow keys.

2. Save your changes.

3. Return to Unity Editor and enter Play Mode to test your updated script. Remember to exit Play mode when you’re done.

Check your code

Before you continue, check that your updated Update function matches the reference code below:

void Update()
{
    float horizontal = 0.0f;
    if (Keyboard.current.leftArrowKey.isPressed)
    {
        horizontal = -1.0f;
    }
    else if (Keyboard.current.rightArrowKey.isPressed)
    {
        horizontal = 1.0f;
    }
    
    Debug.Log(horizontal);



    Vector2 position = transform.position;
    position.x = position.x + 0.1f * horizontal;
    transform.position = position;
}

Note: If you added vertical movement as an extension when you first set up this script, you may have additional lines of code in your script.

5. Challenge: Set up vertical movement using keyboard input

Now that you’ve set up horizontal movement, repeat the process that you just followed to add vertical movement using the Up arrow and Down arrow keys for input.

Use the following tips to help you if you need a little more guidance:

  • Check that every instruction you write ends with a semicolon.
  • Check that your instructions are inside the braces of the Update function.
  • Check that you declared a new variable for the vertical input.
  • Check for any typos in property names, including the use of uppercase and lowercase letters. The Console window will display an error if Unity can’t find a required property — when this happens, the cause is often a typo.

When you’ve finished, test your updated script in Unity Editor before continuing. You should now be able to move the player character diagonally by pressing a vertical arrow key and a horizontal arrow key at the same time!

The reference script at the end of this tutorial includes both vertical and horizontal movement.

6. Check your script

Take a moment to check that your script is correct before continuing.

PlayerController.cs

Important: If you completed any extension work in your script, this will not be reflected in the reference script below.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;


public class PlayerControllerTutorialUpdates : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{


}


// Update is called once per frame
void Update()
{
    float horizontal = 0.0f;
    if (Keyboard.current.leftArrowKey.isPressed)
    {
        horizontal = -1.0f;
 	    }
    else if (Keyboard.current.rightArrowKey.isPressed)
    {
        horizontal = 1.0f;
    }
    Debug.Log(horizontal);


    float vertical = 0.0f;
    if (Keyboard.current.upArrowKey.isPressed)
    {
        vertical = 1.0f;
    }
    else if (Keyboard.current.downArrowKey.isPressed)
    {
        vertical = -1.0f;
    }
    Debug.Log(vertical);


    Vector2 position = transform.position;
    position.x = position.x + 0.1f * horizontal;
    position.y = position.y + 0.1f * vertical;
    transform.position = position;
}

}

7. Next steps

You’ve now implemented basic movement by reading keyboard input from the player — a great start and very useful for prototyping! Next you’ll build on that by using specific Input System functionality to control movement in a way that can be scaled for multiple different input devices.

Complete this tutorial