# Start a new game

> Build the input layer of a new web game with @gamepadly/sdk so every action works on controller, keyboard and mouse, with haptics, DualSense adaptive triggers and a test that runs without a controller.

Source: https://gamepadly.com/sdk/start/quick-start

When you write the game's input code yourself, bind actions instead of keys: each action lists every
controller button, key and mouse button that triggers it, and the game asks "did the player jump?" once per
frame. This page builds that layer with movement, a fire button, haptics, adaptive triggers and a test.
Adding a controller to a game that already exists? Start with [Add a controller in 5 minutes](https://gamepadly.com/sdk/start/add-controller).

## 1. Create the hub

```ts
import { createGamepadly } from '@gamepadly/sdk';

const hub = createGamepadly();
const p1 = hub.player(0); // P1; hub.player(1) is P2, up to four players
```

Create one hub per page. It tracks controllers being plugged in and out and resets rumble and triggers when the
page closes. No permission prompt appears: every controller the browser exposes through the Gamepad API works.

## 2. Map inputs to actions

```ts
const actions = p1.createActions({
  actions: {
    fire: ['r2', 'Space', 'MouseLeft'],
    jump: ['south', 'KeyW', 'ArrowUp'],
    pause: ['start', 'Escape'],
  },
  axes: {
    moveX: { stick: 'lx', negativeKeys: ['KeyA', 'ArrowLeft'], positiveKeys: ['KeyD', 'ArrowRight'] },
  },
});
```

A binding is a button name (`south` is A on Xbox, Cross on PlayStation and B on Nintendo; see
[Buttons and layouts](https://gamepadly.com/sdk/guides/buttons-and-layouts)), an analog trigger (`l2`, `r2`), a stick direction
(`lx+`, `ly-`, ...), a `KeyboardEvent.code`, or `MouseLeft` / `MouseRight` / `MouseMiddle`.

## 3. Read actions in your loop

```ts
import { createGameLoop } from '@gamepadly/sdk/loop';

const SPEED = 240;
const player = { x: 0, jump() {}, fire() {} };

const loop = createGameLoop({
  fixedStep: 1 / 60,
  onUpdate(dt, now) {
    actions.update(p1.input.getState(), now); // once per update, before reading actions

    player.x += actions.axis('moveX') * SPEED * dt; // -1..1, stick or keys
    if (actions.justPressed('jump')) player.jump();
    if (actions.justPressed('fire')) {
      player.fire();
      p1.haptics.playPreset('recoil', { pan: 0.3 }); // returns which output played
    }
  },
  onRender() {
    // draw
  },
});
loop.start();
```

`createGameLoop` is optional: call `actions.update()` from any loop you already have, such as a Three.js
`renderer.setAnimationLoop` callback or a Phaser scene's `update` (see the [Three.js](https://gamepadly.com/sdk/recipes/three-js) and
[Phaser](https://gamepadly.com/sdk/recipes/phaser) recipes). `axis()` applies a small deadzone; raw stick values are in
`p1.input.getState()`.

## 4. Show what to press

Browsers hide controllers until the player presses a button. Show a hint until one appears, and label buttons
the way they are printed on the controller in the player's hands:

```ts
import { getButtonLabel } from '@gamepadly/sdk';

function renderHint() {
  const brand = p1.getCapabilities().identity.brand;
  hint.textContent = p1.input.getState().connected
    ? `${getButtonLabel('south', brand)} to jump, ${getButtonLabel('r2Btn', brand)} to fire` // "A … RT" or "Cross … R2"
    : 'Press any button on your controller';
}
renderHint();
hub.onCapabilitiesChange(renderHint);
```

## 5. Offer the console features

DualSense adaptive triggers, gyro and touchpad, and Switch Pro HD Rumble, need one WebHID permission in desktop
Chrome or Edge. The browser only opens its device picker from a click:

```ts
connectButton.hidden = !('hid' in navigator);
connectButton.addEventListener('click', () => void hub.connectWebHID());
void hub.reconnectAuthorized(); // no prompt for controllers approved on an earlier visit

const applyTriggers = () => p1.triggers.applyPreset('weapon', 'right');
applyTriggers();
hub.onCapabilitiesChange(applyTriggers); // trigger effects apply once WebHID is connected
```

On controllers without adaptive triggers these calls do nothing, so the same code runs everywhere.

## 6. Test without a controller

```ts
import { expect, it } from 'vitest';
import { createMockPlayerHandle } from '@gamepadly/sdk/game';

it('jumps on the south button and fires with haptics', () => {
  const pad = createMockPlayerHandle({ brand: 'sony' });
  const actions = pad.createActions({
    actions: { jump: ['south', 'Space'], fire: ['r2', 'MouseLeft'] },
  });

  pad.state.buttons.cross = true; // south
  pad.state.r2 = 1;
  actions.update(pad.input.getState(), 16);

  expect(actions.justPressed('jump')).toBe(true);
  expect(actions.justPressed('fire')).toBe(true);
  expect(pad.haptics.playPreset('recoil')).toBe('4ch_vcm'); // a DualSense with 4-channel audio
});
```

`createMockPlayerHandle({ brand })` reports realistic capabilities for `'sony'`, `'xbox'`, `'nintendo'` and
`'generic'`, and the test runs in plain Node. Games written against the portable game contract can use
`createMockGameSDK()` instead: see [Games and testing](https://gamepadly.com/sdk/guides/games-and-testing).

## 7. Clean up

```ts
function destroy() {
  loop.dispose();
  actions.dispose();
  hub.dispose(); // stops rumble and resets triggers and lightbar on every controller
}
```

In React, create the hub in `useEffect` and call `destroy()` in its cleanup. StrictMode mounts effects twice in
development, so anything created outside the effect leaks a second hub. The [React](https://gamepadly.com/sdk/recipes/react) recipe
shares one hub through a provider.

## Next steps

- [Haptics](https://gamepadly.com/sdk/guides/haptics) and [Adaptive triggers](https://gamepadly.com/sdk/guides/adaptive-triggers) list every preset.
- [Multiple players](https://gamepadly.com/sdk/guides/multiplayer) covers P2 to P4 and hot-plugging.
- [Examples](https://gamepadly.com/sdk/examples) has complete single-file pages to copy.
