我正在尝试扩展本机 GamepadAPI 以包含自定义控制器代码。
使用 TypeScript,我实现了一个简单的函数来调度“gamepadconnected”事件。
// simulate gamepadconnected event
function dispatchGamepadConnectedEvent() {
let gamepad = Object.create(Gamepad.prototype);
console.log(gamepad);
let event = new GamepadEvent('gamepadconnected', {
gamepad: gamepad
})
window.dispatchEvent(event);
console.log('Gamepad connect event dispatched.');
}
但是,在调度事件时,我收到一个错误:
Gamepad {}axes: (...)buttons: (...)connected: (...)id: (...)index: (...)mapping: (...)timestamp: (...)vibrationActuator: (...)__proto__: Gamepad
extension.ts:37 Uncaught TypeError: Failed to construct 'GamepadEvent': member gamepad is not of type Gamepad.
at dispatchGamepadConnectedEvent (extension.ts:37)
at extension.ts:48
尽管实例化的 Gamepad 对象看起来不错,但 Gamepad 的类型并不正确。为什么会这样?如何创建一个新的、正确的 Gamepad 对象来触发本机事件?