# Phaser

> Add controller support to a Phaser game with @gamepadly/sdk. Make an existing keyboard game playable on a controller with the bridge, or read an action map in a scene's update, with haptics panned to where things happen and cleanup on scene shutdown.

Source: https://gamepadly.com/sdk/recipes/phaser

There are two ways to add a controller to a Phaser game. If the game already reads the keyboard through
`this.input.keyboard`, the bridge presses those keys from the controller and the scenes do not change. If you are
writing the input code, read an action map in the scene's `update()`. The code runs on Phaser 4 and uses only APIs that Phaser 3 also has.

```bash
npm install @gamepadly/sdk phaser
```

## A game that already uses the keyboard

This scene only knows about the arrow keys and Space. The three lines at the bottom make it playable on any
controller: the D-pad and left stick press the arrows, and the bottom face button presses Space and plays a
light click.

```ts
import Phaser from 'phaser';
import { createGamepadly } from '@gamepadly/sdk';
import { createKeyMouseBridge } from '@gamepadly/sdk/bridge';

class PlayScene extends Phaser.Scene {
  private cursors!: Phaser.Types.Input.Keyboard.CursorKeys;
  private ship!: Phaser.GameObjects.Rectangle;

  create() {
    this.cursors = this.input.keyboard!.createCursorKeys();
    this.ship = this.add.rectangle(400, 520, 48, 24, 0x0a84ff);
  }

  update(_time: number, delta: number) {
    const dx = (this.cursors.right.isDown ? 1 : 0) - (this.cursors.left.isDown ? 1 : 0);
    this.ship.x = Phaser.Math.Clamp(this.ship.x + dx * 0.4 * delta, 24, 776);
    if (Phaser.Input.Keyboard.JustDown(this.cursors.space)) {
      bridge.triggerHaptic('recoil', { pan: panOf(this, this.ship.x) });
      // ... fire
    }
  }
}

// Pan from -1 (left edge of the camera's view) to 1 (right edge).
function panOf(scene: Phaser.Scene, worldX: number): number {
  const view = scene.cameras.main.worldView;
  return Phaser.Math.Clamp(((worldX - view.x) / view.width) * 2 - 1, -1, 1);
}

new Phaser.Game({ type: Phaser.AUTO, width: 800, height: 600, scene: PlayScene });

// The controller: the bridge presses the arrow keys and Space for the scene.
const hub = createGamepadly();
const bridge = createKeyMouseBridge({ player: hub, profile: 'platformer' });
bridge.start();
```

Phaser identifies keys by `event.keyCode` and listens on `window`. The bridge fills in `keyCode` for every key it
presses and sends the events where `window` receives them, so `createCursorKeys()`, `addKey()` and `JustDown()` all
work. If the game sets `input.keyboard.target` to the canvas, pass the same element as the bridge's `keyTarget`.

The `'platformer'` profile maps the D-pad and left stick to the arrows, the bottom face button to Space, and the
left face button to Z. For other keys, write a profile: see
[Add a controller in 5 minutes](https://gamepadly.com/sdk/start/add-controller).

## New input code: an action map

When you write the scene's input yourself, bind each action to controller buttons and keys at once, and read it in
`update()`:

```ts
import Phaser from 'phaser';
import { createGamepadly, type ActionTracker } from '@gamepadly/sdk';

// One hub per page, outside the scenes, so it survives scene restarts.
const hub = createGamepadly();
const p1 = hub.player(0);

class PlayScene extends Phaser.Scene {
  private actions!: ActionTracker<'fire' | 'pause', 'moveX'>;
  private ship!: Phaser.GameObjects.Rectangle;

  create() {
    this.ship = this.add.rectangle(400, 520, 48, 24, 0x0a84ff);
    this.actions = p1.createActions({
      actions: {
        fire: ['south', 'r2', 'Space'],
        pause: ['start', 'Escape'],
      },
      axes: {
        moveX: { stick: 'lx', negativeButtons: ['left'], positiveButtons: ['right'], negativeKeys: ['ArrowLeft', 'KeyA'], positiveKeys: ['ArrowRight', 'KeyD'] },
      },
    });
    // A scene's objects go away on shutdown (scene.restart(), scene.start('Other')), and so must its actions.
    this.events.once(Phaser.Scenes.Events.SHUTDOWN, () => this.actions.dispose());
  }

  update(time: number, delta: number) {
    this.actions.update(p1.input.getState(), time); // once per update, before reading actions

    this.ship.x = Phaser.Math.Clamp(this.ship.x + this.actions.axis('moveX') * 0.4 * delta, 24, 776);
    if (this.actions.justPressed('fire')) {
      p1.haptics.playPreset('recoil', { pan: (this.ship.x / 800) * 2 - 1 });
      // ... fire
    }
    if (this.actions.justPressed('pause')) this.scene.pause();
  }
}

const game = new Phaser.Game({ type: Phaser.AUTO, width: 800, height: 600, scene: PlayScene });
game.events.once(Phaser.Core.Events.DESTROY, () => hub.dispose());
```

A paused scene stops calling `update()`, so it cannot read the button that unpauses it. Read the pause action in a
scene that keeps running, such as a UI scene launched in parallel, and call `this.scene.resume('PlayScene')` from
there.

## Phaser's own gamepad plugin

You do not need it: the SDK reads the controller itself. Phaser leaves its gamepad plugin off unless the game config
sets `input: { gamepad: true }`. A game that already uses it can keep it for input and call the SDK only for haptics,
adaptive triggers and button labels. Create the hub as above and call `p1.haptics.playPreset()` where things happen.

## Next steps

- [Start a new game](https://gamepadly.com/sdk/start/quick-start) adds button prompts that match the player's controller, a "press any
  button" hint, DualSense adaptive triggers and a test that runs without a controller.
- [Haptics](https://gamepadly.com/sdk/guides/haptics) lists every preset, and [Multiple players](https://gamepadly.com/sdk/guides/multiplayer) covers local
  co-op with `hub.player(1)` and up.
