Game Input: Actions, Gamepads and Touch
A game reads actions, not keys. jump is Space on a keyboard, A on an Xbox pad, Cross on a PlayStation pad and a Jump button on a phone, all at once, with nothing extra in the script. Since spatial-ecs 0.18.0 (SPATIAL_ECS_FEATURES.gameInput).
import { Behaviour } from "@relu-interactives/spatial-ecs";
export default class Player extends Behaviour {
onUpdate() {
const input = this.input;
if (!input) return;
// { x: right, y: forward }, each -1..1: WASD, arrows, left stick, D-pad or the touch stick
const move = input.getAxis("move");
// Pixels this frame, y down, exactly like getMouseDelta(): the mouse, the right stick or a finger
const look = input.getAxis("look");
if (input.getActionDown("jump")) {
// pressed this frame, on any device
}
if (input.getAction("fire")) {
// held
}
const pull = input.getActionValue("aim"); // 0..1, a trigger's pull
void move; void look; void pull;
}
}this.input is the world's InputSystem (also this.world.input). It's null only when the host built the world without one. The key and mouse methods in Reading Input still work and read the same devices.
Actions every game has
| Action | Kind | Keyboard and mouse | Gamepad | Touch |
|---|---|---|---|---|
move | axis | WASD, arrow keys | left stick, D-pad | stick |
look | axis | mouse movement | right stick | drag on the right half |
jump | button | Space | south (A / Cross) | jump button |
fire | button | left click | RT / R2 | fire button |
aim | button | right click | LT / L2 | aim button |
interact | button | E | west (X / Square) | interact button |
reload | button | R | north (Y / Triangle) | reload button |
sprint | button | Left Shift | left stick click | sprint button |
crouch | button | C | east (B / Circle) | crouch button |
pause | button | Esc, P | Start / Options | pause button |
confirm | button | Enter, Space | south | (tap the button) |
back | button | Esc, Backspace | east | |
next / previous | button | E / Q | RB / LB | |
navigate | axis | arrows, WASD | D-pad, left stick |
look is in pixels, y down, so a camera written for the mouse (yaw -= look.x * 0.002) turns at a sensible speed with a stick, where it's integrated over time with a gentle curve, or a finger. The player's look sensitivity and invert-Y (in settings) apply to look only.
confirm, back, next, previous and navigate are for menus and are kept apart from gameplay, so rebinding jump never breaks a menu.
Your own actions
import { Behaviour } from "@relu-interactives/spatial-ecs";
export default class Dash extends Behaviour {
protected init() {
this.input?.defineActions({
dash: { kind: "button", bindings: ["key:KeyQ", "pad:rb", "touch:dash"] },
});
}
onUpdate() {
if (this.input?.getActionDown("dash")) {
// dash
}
}
}A binding is a short string:
| Binding | Means |
|---|---|
key:Space, key:KeyW, key:ShiftLeft | a key, by KeyboardEvent.code |
mouse:left, mouse:right, mouse:middle | a mouse button |
pad:south, pad:east, pad:west, pad:north | the face buttons by position (A B X Y on Xbox) |
pad:lb, pad:rb, pad:lt, pad:rt, pad:ls, pad:rs, pad:select, pad:start | shoulders, triggers, stick clicks, the middle buttons |
pad:dpadUp … pad:dpadRight | the D-pad as buttons |
touch:<id> | an on-screen button by its id |
keys:KeyW,KeyS,KeyA,KeyD | four keys as a direction: up, down, left, right |
pad:leftStick, pad:rightStick, pad:dpad | a stick or the D-pad as a direction |
mouse:delta, touch:stick, touch:look | mouse movement, the touch stick, a look drag |
Names like pad:a, pad:cross and pad:r2 work too and mean the same position.
Gamepads
Any pad the browser reports with the standard mapping works: Xbox, PlayStation (DualShock 4, DualSense), Switch Pro, and most others. Sticks have a radial dead zone (0.15), triggers are analog and count as pressed from halfway, and pads are read every frame, so plugging one in mid-game just works. Every connected pad drives the same actions.
import { Behaviour } from "@relu-interactives/spatial-ecs";
export default class Pads extends Behaviour {
private stop: (() => void) | null = null;
protected init() {
this.stop =
this.input?.onGamepadChange((pad) => {
console.log(pad.family, pad.connected ? "connected" : "disconnected"); // "xbox", "playstation", "switch", "generic"
}) ?? null;
}
onHit() {
this.input?.rumble(0.8, 0.4, 150); // strong, weak, ms; vibrates a phone too. Off when the player turned vibration off.
}
dispose() {
this.stop?.();
}
}Prompts that match the device
The input system knows the device the player used last and the family of their pad. Use it for every on-screen hint, so a pad player sees "Press A" and a phone player sees "Tap Jump":
import { Behaviour } from "@relu-interactives/spatial-ecs";
export default class Hint extends Behaviour {
private label: HTMLElement | null = null;
protected init() {
this.label = document.createElement("span");
document.getElementById("relu-ui")?.appendChild(this.label);
this.show();
this.input?.onDeviceChange(() => this.show());
}
private show() {
const prompt = this.input?.getPrompt("interact");
if (!this.label || !prompt) return;
// prompt.device: "keyboard" | "mouse" | "gamepad" | "touch"
// prompt.label: "E", "X", "Square", "Interact"; prompt.symbol: "□" on PlayStation
const verb = prompt.device === "touch" ? "Tap" : "Press";
this.label.textContent = `${verb} ${prompt.symbol} to open`;
}
dispose() {
this.label?.remove();
}
}The page's root element also carries data-relu-input="keyboard|mouse|gamepad|touch" and data-relu-pad="xbox|playstation|switch|generic", so CSS can swap glyphs and show focus rings only for pads:
[data-relu-input="gamepad"] .menu button:focus { outline: 2px solid var(--accent); }
[data-relu-input="touch"] .key-hint { display: none; }Menus with a pad or keyboard
getNavigation() gives one step ("up" | "down" | "left" | "right") the frame a direction is pushed, then repeats while it's held. Read it with confirm and back in onPausedUpdate for a pause menu, or in onUpdate for a main menu:
import { Behaviour } from "@relu-interactives/spatial-ecs";
export default class PauseMenu extends Behaviour {
private buttons: HTMLButtonElement[] = [];
private index = 0;
onUpdate() {
if (this.input?.getActionDown("pause")) this.world.pause();
}
onPausedUpdate() {
const input = this.input;
if (!input) return;
const step = input.getNavigation();
if (step === "down") this.index = (this.index + 1) % this.buttons.length;
if (step === "up") this.index = (this.index - 1 + this.buttons.length) % this.buttons.length;
this.buttons[this.index]?.focus();
if (input.getActionDown("confirm")) this.buttons[this.index]?.click();
if (input.getActionDown("back") || input.getActionDown("pause")) this.world.resume();
}
}Rebinding
import { Behaviour } from "@relu-interactives/spatial-ecs";
export default class ControlsScreen extends Behaviour {
async rebindJump() {
// Waits for the next key, mouse button or pad button. Esc or 8 s gives null.
const binding = await this.input?.captureBinding({ devices: ["keyboard", "gamepad"] });
if (!binding) return;
const current = this.input?.getActionBindings("jump") ?? [];
// Keep the touch button and replace the binding from the same device.
const kind = binding.split(":")[0];
const next = [binding, ...current.filter((b) => !b.startsWith(`${kind}:`))];
this.input?.rebind("jump", next); // saved to settings.controls.bindings
}
resetAll() {
this.input?.resetBindings();
}
}Rebinds are saved in the player's settings and come back next visit. Only actions the player changed are saved, so a game update that adds a binding still reaches everyone else.
Touch controls
On phones and tablets the engine draws its own controls when the host asks for them: a movement stick on the left (it appears where the thumb lands), a look area on the right half, action buttons under the right thumb, and a pause button in the corner. Each control follows its own finger, so moving, looking and pressing work together. They show while touch is the last input, hide when a keyboard or pad is used, and hide while the world is paused so a menu can take the screen.
The template turns them on for projects that target phones. A script picks the buttons the game needs, most important first:
import { Behaviour } from "@relu-interactives/spatial-ecs";
export default class TouchLayout extends Behaviour {
protected init() {
this.input?.touch?.configure({
stick: "float", // or "fixed", or false for none
look: true, // drag on the right half to look
buttons: [{ id: "jump" }, { id: "fire" }, { id: "interact", label: "Use" }],
pause: true,
});
}
}Buttons bind as touch:<id>; the defaults already bind jump, fire, aim, interact, reload, sprint, crouch and pause, which also have built-in icons. Up to five buttons fit. The first is the large one.
this.input.touch is null when the host has no touch controls. setVisibility("always" | "never" | "auto") overrides when they show. Opacity, size and floating or fixed stick come from the player's settings (controls.touchOpacity, touchScale, touchStick).
The controls are themed with CSS variables on .relu-touch, so a game's UI can match them:
.relu-touch {
--relu-touch-fill: rgba(20, 24, 32, 0.35);
--relu-touch-fill-pressed: rgba(255, 196, 64, 0.45);
--relu-touch-stroke: rgba(255, 255, 255, 0.5);
--relu-touch-accent: #ffc440;
--relu-touch-ink: #fff;
--relu-touch-font: 600 12px/1.1 "Your UI Font", sans-serif;
}The look area covers the right half, so taps there don't reach the 3D scene. A game whose players tap things in the world (a puzzle, a point-and-click) sets look: false and reads taps through onSelect or the mouse methods.
Host setup
import { InputSystem } from "@relu-interactives/spatial-ecs";
const input = new InputSystem({
gamepad: true, // default
touch: { buttons: [{ id: "jump" }] }, // or true for the defaults, false (default) for none
touchVisibility: "auto",
});
