There are two ways to read input, and most games use both:
- Polling asks "is this held right now?" inside
export function update()Screen.OnUpdate()def update(). Use it for continuous things like movement, aiming and holding to charge. - Events say "this just happened" once per press. Use them for one-off actions like jumping, shooting, menus and toggles.
| You want to… | Use |
|---|---|
| Move while an arrow key is held | input.isKeyDown()Input.IsKeyDown()isKeyDown() in export function update()Screen.OnUpdate()def update() |
| Jump once when Space is pressed | export function onKeyDown()Input.OnKeyDown()def keyDown() |
| Paint while the mouse button is held | input.isMouseDown()Input.IsMouseDown()isMouseDown() in export function update()Screen.OnUpdate()def update() |
| Place a block on click | export function onMouseDown()Input.OnMouseDown()def mouseDown() |
| Follow a finger | input.touchX()Input.TouchX()touchX() / input.touchY()Input.TouchY()touchY() in export function update()Screen.OnUpdate()def update() |
| React when a finger lands | export function onTouchStart()Input.OnTouchStart()def touchStart() |
#Keyboard
Keys are named like the browser's KeyboardEvent.key: "a", "A" (with Shift), "ArrowLeft", " " (Space), "Enter", "Shift", "Escape".
Letter case matters
With Shift or Caps Lock on, pressing A reports "A", not "a". Check both if that matters to your game.
#Mouse
input.mouseX()Input.MouseXmouseX() and input.mouseY()Input.MouseYmouseY() are the pointer's position in canvas pixels. Buttons are numbered 0 (left), 1 (middle) and 2 (right).
#Touch
On phones and tablets every finger gets an id that stays the same until it lifts. Touch events give you the id and position. Use input.touchCount()Input.TouchCount()touchCount(), input.isTouchDown()Input.IsTouchDown()isTouchDown(), input.touchX()Input.TouchX()touchX() and input.touchY()Input.TouchY()touchY() to poll.
input.touchX()Input.TouchX()touchX() and input.touchY()Input.TouchY()touchY() return -1 for an id that isn't down. There's a full multi-touch example on the Examples page.
#Supporting mouse and touch
To keep a game playable everywhere, treat a tap like a click. Handle both export function onMouseDown()Input.OnMouseDown()def mouseDown() and export function onTouchStart()Input.OnTouchStart()def touchStart() and call the same function from each. Also keep important buttons large, since fingers are less precise than a cursor.
Keyboard focus
Keyboard events only reach your codetoy after the preview has focus. If keys don't respond, click the canvas once. Embeds and Discord work the same way.