# 在 Phaser 中接入手柄

> 用 @gamepadly/sdk 给 Phaser 游戏接入手柄。用桥接模块让已有的键盘游戏支持手柄，或者在场景的 update 里读取动作映射；触觉按事件位置设置声像，场景关闭时清理资源。

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

给 Phaser 游戏接入手柄有两种方式。如果游戏已经通过 `this.input.keyboard` 读取键盘，桥接模块会用手柄按下这些键，场景代码不用改。如果你正在写输入代码，就在场景的 `update()` 里读取动作映射。代码在 Phaser 4 上运行，只用到 Phaser 3 也有的 API。

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

## 已经用键盘的游戏

这个场景只认识方向键和空格。底部的三行让它能用任何手柄玩：十字键和左摇杆按下方向键，下方的面键按下空格，并播放一下轻微的点击震动。

```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) });
      // ... 开火
    }
  }
}

// 声像从 -1（镜头视野左边缘）到 1（右边缘）。
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 });

// 手柄：桥接模块替场景按下方向键和空格。
const hub = createGamepadly();
const bridge = createKeyMouseBridge({ player: hub, profile: 'platformer' });
bridge.start();
```

Phaser 用 `event.keyCode` 识别按键，并在 `window` 上监听。桥接模块为每个按下的键填好 `keyCode`，并把事件发到 `window` 能收到的地方，所以 `createCursorKeys()`、`addKey()` 和 `JustDown()` 都能正常工作。如果游戏把 `input.keyboard.target` 设成了 canvas，就把同一个元素作为桥接模块的 `keyTarget` 传入。

`'platformer'` 配置把十字键和左摇杆映射到方向键，下方的面键映射到空格，左边的面键映射到 Z。其他按键需要自己写配置，见 [5 分钟给游戏接入手柄](https://gamepadly.com/sdk/zh/start/add-controller)。

## 新写的输入代码：动作映射

自己写场景的输入时，把每个动作同时绑定到手柄按键和键盘按键，并在 `update()` 里读取：

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

// 每个页面一个 hub，放在场景外面，这样场景重启后它还在。
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'] },
      },
    });
    // 场景关闭时（scene.restart()、scene.start('Other')）它的对象会被移除，动作映射也要一起释放。
    this.events.once(Phaser.Scenes.Events.SHUTDOWN, () => this.actions.dispose());
  }

  update(time: number, delta: number) {
    this.actions.update(p1.input.getState(), time); // 每次 update 一次，在读取动作之前

    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 });
      // ... 开火
    }
    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());
```

暂停的场景不再调用 `update()`，所以读不到取消暂停的按键。在一个持续运行的场景里读取暂停动作，比如并行启动的 UI 场景，再从那里调用 `this.scene.resume('PlayScene')`。

## Phaser 自带的手柄插件

你不需要它：SDK 自己读取手柄。除非游戏配置里设置了 `input: { gamepad: true }`，Phaser 不会启用手柄插件。已经在用它的游戏可以继续用它读取输入，只在触觉、自适应扳机和按键名称上调用 SDK。按上面的方式创建 hub，在事件发生的地方调用 `p1.haptics.playPreset()` 即可。

## 下一步

- [开发新游戏](https://gamepadly.com/sdk/zh/start/quick-start)介绍了与玩家手柄一致的按键提示、“按任意键”提示、DualSense 自适应扳机，以及不接手柄也能运行的测试。
- [触觉反馈](https://gamepadly.com/sdk/zh/guides/haptics)列出了所有预设，[多名玩家](https://gamepadly.com/sdk/zh/guides/multiplayer)介绍了用 `hub.player(1)` 及以后的句柄实现本地合作。
