useGamepad
检测和监听游戏手柄的连接状态,实时获取按钮和摇杆数据。
前置依赖
依赖参数
| 参数名 | 类型 | 说明 |
|---|---|---|
deps.vue.ref | <T>(value: T) => Ref<T> | Vue ref 函数 |
deps.vue.onMounted | (fn: () => void) => void | Vue onMounted 钩子 |
deps.vue.onUnmounted | (fn: () => void) => void | Vue onUnmounted 钩子 |
deps.navigator | GamepadAPI | Navigator Gamepad API |
deps.window | WindowWithGamepad | Window 对象 |
环境要求
浏览器 API: Gamepad API
支持所有主流浏览器,包括 Chrome、Firefox、Edge、Safari 等。
函数签名
typescript
function useGamepad(
deps: UseGamepadDeps
): UseGamepadReturn
interface UseGamepadDeps {
vue: VueCompositionAPI
navigator: GamepadAPI
window: WindowWithGamepad
}
interface UseGamepadReturn {
isSupported: Ref<boolean>
gamepads: Ref<GamepadInfo[]>
error: Ref<string | null>
}
interface GamepadInfo {
id: string
index: number
connected: boolean
buttons: GamepadButton[]
axes: number[]
timestamp: number
}参数
| 参数名 | 类型 | 必填 | 说明 |
|---|---|---|---|
deps | UseGamepadDeps | 是 | 依赖注入对象 |
返回值
| 属性 | 类型 | 说明 |
|---|---|---|
isSupported | Ref<boolean> | 是否支持 Gamepad API |
gamepads | Ref<GamepadInfo[]> | 已连接的手柄列表 |
error | Ref<string | null> | 错误信息 |
工作原理
- 检查浏览器是否支持 Gamepad API
- 监听手柄连接和断开事件
- 使用 requestAnimationFrame 实时轮询手柄状态
- 获取所有已连接手柄的按钮和摇杆数据
- 组件卸载时停止轮询并清理监听器
支持的手柄:
- Xbox Series X/S、Xbox One 手柄
- PlayStation 5、PlayStation 4 手柄
- Nintendo Switch Pro 手柄
- 第三方兼容手柄
数据说明:
buttons: 按钮数组,每个按钮包含pressed、touched、value属性axes: 摇杆轴数组,值范围 -1 到 1(0 为中心位置)timestamp: 最后更新时间戳
异常
无异常抛出