跳转到内容

在 React 中接入手柄

在 React 里,SDK 放在 effect 中:整个应用只创建一次 hub,游戏循环在 effect 里运行,只在界面显示的内容变化时才重新渲染,比如连接的是哪款手柄。这一页依次搭建这三部分。代码只用到 hooks 和 createRoot,所以需要 React 18 或更高版本。

终端窗口
npm install @gamepadly/sdk
'use client'; // Next.js App Router:provider 用到了 hooks。其他环境会忽略这一行。
import { createContext, useContext, useEffect, useState, type ReactNode } from 'react';
import { createGamepadly, type GamepadlyHub } from '@gamepadly/sdk';
const GamepadlyContext = createContext<GamepadlyHub | null>(null);
export function GamepadlyProvider({ children }: { children: ReactNode }) {
const [hub, setHub] = useState<GamepadlyHub | null>(null);
useEffect(() => {
const created = createGamepadly();
setHub(created);
return () => created.dispose(); // 停止震动并复位扳机
}, []);
return <GamepadlyContext.Provider value={hub}>{children}</GamepadlyContext.Provider>;
}
/** 应用的 hub;provider 的 effect 运行之前为 null。 */
export function useGamepadly(): GamepadlyHub | null {
return useContext(GamepadlyContext);
}

在靠近根的位置包一层,只包一次:

import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
import { GamepadlyProvider } from './gamepadly';
import { Game } from './Game';
createRoot(document.getElementById('root')!).render(
<StrictMode>
<GamepadlyProvider>
<Game />
</GamepadlyProvider>
</StrictMode>,
);

为什么用 effect,而不是 useMemo 或在模块顶层调用 createGamepadly():

  • StrictMode 在开发环境里会把每个 effect 挂载两次:effect、清理、effect。清理释放了第一个 hub,第二次 effect 创建一个新的,所以始终只有一个 hub 在运行。在渲染过程中创建的 hub 永远不会被释放。
  • 服务端渲染(Next.js、Remix、Astro islands)从不运行 effect,所以服务端不会访问 navigator。在 effect 运行之前,useGamepadly() 返回 null。
  • 每个页面一个 hub。 把 provider 放在所有用到手柄的组件之上,而不是放在会挂载又卸载的组件里。

游戏状态放在 effect 里,不要放进 React state。每秒调用 60 次 setState 会让组件树每帧都重新渲染;而在循环里直接画到 canvas 上完全不触发渲染。

import { useEffect, useRef } from 'react';
import { useGamepadly } from './gamepadly';
export function Game() {
const hub = useGamepadly();
const canvasRef = useRef<HTMLCanvasElement>(null);
useEffect(() => {
const canvas = canvasRef.current;
if (!hub || !canvas) return;
const ctx = canvas.getContext('2d')!;
const p1 = hub.player(0);
const actions = p1.createActions({
actions: { fire: ['south', 'r2', 'Space'] },
axes: { moveX: { stick: 'lx', negativeButtons: ['left'], positiveButtons: ['right'], negativeKeys: ['ArrowLeft'], positiveKeys: ['ArrowRight'] } },
});
const ship = { x: 300 };
let frame = requestAnimationFrame(function tick(now) {
actions.update(p1.input.getState(), now); // 每帧一次,在读取动作之前
ship.x = Math.max(20, Math.min(580, ship.x + actions.axis('moveX') * 6));
if (actions.justPressed('fire')) p1.haptics.playPreset('recoil', { pan: ship.x / 300 - 1 });
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = '#0a84ff';
ctx.fillRect(ship.x - 20, 250, 40, 20);
frame = requestAnimationFrame(tick);
});
return () => {
cancelAnimationFrame(frame);
actions.dispose(); // 移除它的键盘监听
};
}, [hub]);
return <canvas ref={canvasRef} width={600} height={300} />;
}

这个 effect 依赖 hub,所以 provider 创建好 hub 后它才开始运行,在 StrictMode 下也能干净地重启。

界面应该对 Xbox 玩家说“按 A”,对 PlayStation 玩家说“按 Cross”,并且在浏览器报告手柄之前提示玩家按一个键(浏览器在按键之前不会暴露手柄)。这些信息很少变化,所以它是唯一值得放进 React state 的东西:

import { useEffect, useState } from 'react';
import { getButtonLabel, type ControllerBrand } from '@gamepadly/sdk';
import { useGamepadly } from './gamepadly';
export function useController() {
const hub = useGamepadly();
const [controller, setController] = useState<{ connected: boolean; brand: ControllerBrand }>({ connected: false, brand: 'generic' });
useEffect(() => {
if (!hub) return;
const read = () => {
const caps = hub.active.getCapabilities();
setController({ connected: caps.tier !== 'keyboard_mouse', brand: caps.identity.brand });
};
read();
return hub.onCapabilitiesChange(read); // 返回取消订阅的函数
}, [hub]);
return controller;
}
export function FireHint() {
const { connected, brand } = useController();
return <p>{connected ? `按 ${getButtonLabel('south', brand)} 开火` : '按手柄上任意键开始'}</p>;
}

DualSense 自适应扳机和 Switch Pro HD 震动需要一次 WebHID 授权,浏览器只在点击后才会请求:

import { useGamepadly } from './gamepadly';
export function ConnectButton() {
const hub = useGamepadly();
if (!hub || !('hid' in navigator)) return null;
return <button onClick={() => void hub.connectWebHID()}>连接手柄(WebHID)</button>;
}

provider 的用法一样。像上面那样在 useEffect 里创建动作映射,存在 ref 里,然后在 useFrame 开头调用 actions.update()。 Three.js 配方介绍了相对镜头的移动,以及按屏幕位置设置触觉声像。

  • 开发新游戏介绍了自适应扳机,以及不接手柄也能运行的测试。
  • 按键与布局列出了所有按键名和显示名称。
  • 多名玩家介绍了用 hub.player(1) 及以后的句柄实现本地合作。