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:
-
GetKeyDownreturnstruewhen the key started being pressed on this frame. -
GetKeyUpreturnstruewhen the key was released on this frame. -
GetKeyreturnstrueif 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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access