Unity Cookbook. Input handling

Input handling

The two ways: Input Manager

  • Manual: Input
  • There are two ways to get input in Unity
  • The legacy Input Manager
    • uses the Input class
    • uses Directinput
    • works almost always
    • (but sometimes controller axes are screwed up)
    • easier to setup -> this is the one we’ll be using

The two ways: Input system

  • The new Input System
    • Read more on these slides
    • Needs to be installed as a separate package
    • Needs more work to get it running than Input Manager
    • Uses XInput
    • “action-based”
    • We’ll stick to the legacy input manager for now…

  • Here’s a button press event visualized across multiple frames.
  • The colored boxes show which are the frames when the corresponding function returns true.

Keyboard input

More general input

Input table

  • Edit > Project Settings > Input Manager
  • You can change the names, and the buttons that correspond to the names
    • “Fire1” could be changed to “Crouch”, for instance!
  • Positive button refers to a button being pressed
  • Negative button is only needed for directional input
  • You can assign an Alt Button for an alternate input method
  • Note: Keyboard and controller bindings are in their separate entries!
  • Add new entries by increasing the Size property
    • It will duplicate the last entry in the list. Oh wow
  • Use this link to see which button numbers correspond to which controller buttons
    • For example, joystick button 0 is the Xbox button A
    • See button naming convention in Docs: Input manager

Analog input

  • Script Reference: Input.GetAxis
  • how to account for analog sticks? They aren’t buttons you press
    • rather a two-dimensional field of many possible coordinates
    • -> separate input to two axes, vertical and horizontal
    • Sliding scale between -1 and 1
  • Input.GetAxis(axisName)
    • Smoothing with Gravity and Sensitivity
    • Deadzone applied (no input registered if only move the analog stick a bit)
    • float h = Input.GetAxis("Horizontal");

GetAxisRaw

Exercise 1. Player input

Create a top-down player character with a sprite renderer that can

  • change color with the Fire1 button
  • move with the analog stick

Extra: Mouse input

Mouse input example

Extra: Touch input

Extra: Multiplayer input

  • With the input table, you can assign the joystick index for every input with Joy Num
    • $\Rightarrow$ For multiplayer games, you need to create new entries for other players
    • ALSO: you need to set the positive button to “joystick 2 button 0” etc
  • The new Input System handles this a bit more elegantly, see this tutorial: