Bash.tv → GitHub → itch.io

Controller support for browser games through the Gamepad API. Polling each frame, press and release edges, analog triggers with a threshold, round dead zones that remove stick drift, d-pad or stick movement, menu repeat while held, Xbox, PlayStation and Nintendo button names, non-standard layouts, rumble, several players joining with Start and keeping their seat when a controller drops, and the...

Download skill (.zip) Files on GitHub

Gamepad support

If the game uses the game-scaffolding or universal-input-system input layer, it already reads the first controller through actions. Use this module when you need more: several players, button names, rumble, triggers, or menus with repeat.

assets/gamepad.js

import { createGamepads, BTN } from "./gamepad.js";
const pads = createGamepads({ deadzone: 0.18, onConnect: (p) => toast(`${p.style} controller connected`), onDisconnect: () => pause() });
each frame, first: pads.update(dt);
const move = pads.move(0);                       // { x, y, mag }: left stick or d-pad, dead zone applied
if (pads.pressed(0, BTN.A)) jump();              // once per press; down() while held; released() on let go
const gas = pads.value(0, BTN.RT);               // analog trigger 0..1
if (pads.repeat(0, BTN.DOWN, dt)) menu.next();   // press, then repeats after 0.4 s
prompt: `Press ${pads.name(0, BTN.A)}`           // "A", "Cross" or "B" depending on the controller
pads.rumble(0, { strong: 0.8, weak: 0.3, ms: 150 });   // false if the pad can't
lobby: for (const p of pads.list()) if (pads.pressed(p.index, BTN.START)) pads.join(p.index);   // pads.players = seats

BTN uses the standard mapping (what Chrome, Edge, Firefox and Safari report for most controllers): A/Cross = 0, B/Circle = 1, X/Square = 2, Y/Triangle = 3, LB 4, RB 5, LT 6, RT 7, View/Share 8, Menu/Options 9, sticks 10-11, d-pad 12-15. Nintendo’s labels are swapped (A is on the right), so show names from pads.name, and keep “confirm” on button 0 (bottom).

Browser rules

Players

join(index) gives the next free seat; a controller that disconnects keeps its seat (connected: false) and takes it back when the same controller reconnects, even with a new index. Pause the game when a player’s controller drops. For local multiplayer layouts see local-coop.

Tested

Node tests with fake controllers: connecting and style, press/hold/release edges, trigger threshold, dead zone and rescaling, d-pad diagonals, held repeat timing, Xbox/PlayStation/Nintendo names, joining, seats kept on disconnect and reclaimed on reconnect, rumble with and without support, and a throwing getGamepads. The device lab (cross-browser-compatibility) shows connected controllers live: try it with a real controller.

Pitfalls

Reading a stick with no dead zone, hard-coding “Press A” for a PlayStation pad, waiting for the connect event, checking only pad 0, menus that fly by because they act every frame a button is held, and no pause when a controller disconnects.