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
MediumFly the hot air balloon with Keyboard.current and Mouse.current.
- While
rightArrowKeyordKeyisPressed, drift along +x atdriftunits a second;leftArrowKeyoraKey, along -x. bool burnerisspaceKeyorleftButtonpressed; callflame.SetActive(burner);.- Burner on, rise at
rise; off, sink atsink, never belowgroundY.
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
2Buttons and Screens
Buttons and onClickLambdasWiring in the InspectorPanels On and OffHealth BarsRecap: Upgrade Shop5Saving with PlayerPrefs
Save a NumberLoad with a DefaultHigh ScoreSave SettingsRecap: Coins in the Bank3The Game Manager
One Script Runs the GameThe SingletonGame StatesSwitching on the StateRecap: Round Manager6Project: Endless Runner
Three LanesObstacles Ahead9The New Input System
Two Input SystemsKeyboard and MousePressed This FrameInput ActionsRecap: Input SwapPractice on your own: Unity playground