Register custom Gamepad class with GamepadEvent results in Failed to convert value to 'Gamepad'

135 Views Asked by At

I'm trying trying build a little virtual controller as Gamepad class and register it.

For now it is a copy of the Gamepad class:

class MyJoystick {
    readonly axes: ReadonlyArray<number>;
    readonly buttons: ReadonlyArray<GamepadButton>;
    readonly connected: boolean;
    readonly hapticActuators: ReadonlyArray<GamepadHapticActuator>;
    readonly id: string;
    readonly index: number;
    readonly mapping: GamepadMappingType;
    readonly timestamp: DOMHighResTimeStamp;

    constructor() {
        this.axes = [];
        this.buttons = [];
        this.connected = true;
        this.hapticActuators = [];
        this.id = "my-id";
        this.index = 200;
        this.mapping = "standard";
        this.timestamp = Math.floor(Date.now() / 1000);
    }
}

Using

const event = new GamepadEvent("gamepadconnected", {
    gamepad: new MyJoystick() as Gamepad
})
window.dispatchEvent(event);

But I'm getting the following error message:

Failed to construct 'GamepadEvent': Failed to read the 'gamepad' property from 'GamepadEventInit': Failed to convert value to 'Gamepad'.
TypeError: Failed to construct 'GamepadEvent': Failed to read the 'gamepad' property from 'GamepadEventInit': Failed to convert value to 'Gamepad'.

Question: How can I create my own Gamepad class implementation which I can also register with an GamepadEvent?

1

There are 1 best solutions below

0
LickingFilth On

The browser is expecting a real game controller, not just any object that looks like one.

Now, if you're trying to pretend there's a game controller for testing, here are some ideas:

  1. Pretend. Instead of trying to tell the browser there's a real game controller, you can just pretend in your own code. This way, your code thinks there's a game controller, but the browser doesn't get involved.

     const myFakeGamepad = new MyJoystick();
    
     // Tell your code to use the fake game controller
     navigator.getGamepads = function(){
       return [myFakeGamepad];
     };
    
  2. Use a library: There are tools out there that help you pretend there's user input, like a game controller. I recommend the puppeteer. It uses a web browser and can pretend to do things like press buttons.

  3. Hardcore: Change the browser's code. This one is a bit wild, but you could technically change the browser's code to accept your fake game controller. But honestly, that's a lot of work and might be overdoing it.

I'd say the first option is probably your best bet