Chapter 3. Input

Receiving and responding to player input is a defining feature of interactive games. In this chapter, we’ll look at some of the most common input-related problems game developers face. Unity has a wide variety of input methods available, ranging from keyboard and mouse input to gamepad input to more sophisticated systems allowing for mouse pointer control.

3.1 Working with Keyboard Input

Problem

You want to know when the user is pressing keys on a keyboard.

Solution

Use the Input class’s GetKeyDown, GetKeyUp, and GetKey methods to find out what keys are being pressed:

if (Input.GetKeyDown(KeyCode.A))
{
    Debug.Log("The A key was pressed!");
}

if (Input.GetKey(KeyCode.A))
{
    Debug.Log("The A key is being held down!");
}

if (Input.GetKeyUp(KeyCode.A))
{
    Debug.Log("The A key was released!");
}

if (Input.anyKeyDown) {
    Debug.Log("A key was pressed!");
}

Discussion

Each of these methods responds at different times:

  • GetKeyDown returns true when the key started being pressed on this frame.

  • GetKeyUp returns true when the key was released on this frame.

  • GetKey returns true if the key is currently being held down.

You can also use the anyKeyDown property to find out if any key at all is being pressed, which is useful for when you want to ask the player to “press any key to continue.”

3.2 Working with Mouse Input

Problem

You want to know when the mouse moves, as well as where the mouse cursor is on the screen.

Solution

The mouse provides two different kinds ...

Get Unity Game Development Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.