Menu
CoddyTech

Keyboard and Mouse

Part of the Building Real Games section of Coddy's Unity journey. Lesson 45 of 60.

The Input System gives each device an object. Keyboard.current is the keyboard, and every key on it is a control with a name: spaceKey, aKey, upArrowKey, or Keyboard.current[Key.Space] for any key by its Key value. Mouse.current is the mouse, with leftButton, rightButton and position. A control's isPressed is true on every frame it is held down, as Input.GetKey was. This submarine dives and surfaces with the arrows and shines its searchlight while the mouse button is held:

using UnityEngine;
using UnityEngine.InputSystem;

public class Submarine : MonoBehaviour
{
    public float diveSpeed = 2f;
    public Light searchlight;

    void Update()
    {
        Keyboard keyboard = Keyboard.current;
        if (keyboard == null) return;   // no keyboard plugged in

        if (keyboard.downArrowKey.isPressed)
            transform.position += Vector3.down * diveSpeed * Time.deltaTime;
        if (keyboard.upArrowKey.isPressed)
            transform.position += Vector3.up * diveSpeed * Time.deltaTime;

        searchlight.enabled = Mouse.current != null && Mouse.current.leftButton.isPressed;
    }
}

current is the device used last, and it is null when there is none: a phone or a console may have no keyboard, and the null checks keep the script from throwing there. The keyboard has no axes, so the down arrow and S are two separate keys: a submarine that should also dive on S tests keyboard.downArrowKey.isPressed || keyboard.sKey.isPressed. Mouse.current.position.ReadValue() gives the pointer as a Vector2 in screen pixels from the bottom left corner, like Input.mousePosition.

challenge icon

Challenge

Medium

Fly the hot air balloon with Keyboard.current and Mouse.current.

  1. While rightArrowKey or dKey isPressed, drift along +x at drift units a second; leftArrowKey or aKey, along -x.
  2. bool burner is spaceKey or leftButton pressed; call flame.SetActive(burner);.
  3. Burner on, rise at rise; off, sink at sink, never below groundY.

Press Play and fly: hold Space or the mouse button to climb. Then Check.

Try it yourself

using UnityEngine;
using UnityEngine.InputSystem;

public class Balloon : MonoBehaviour
{
    public float drift = 2f;
    public float rise = 3f;
    public float sink = 1f;
    public float groundY = 2f;
    public GameObject flame;

    void Update()
    {
        // drift with the arrows or A and D, burn with Space or the mouse
    }
}

All lessons in Building Real Games

Practice on your own: Unity playground