javascriptgamepad

Construct a Gamepad in js


So I was trying to simulate a controller in JavaScript but couldn't find a way to construct a new Gamepad() and could not figure out how to work this out from the docs could anybody help.

This is what my current code looks like:

function simulateControllerInput(key) {
    const mapping = keyMappings[key];
    if (mapping) {
        const simulatedGamepad = new Gamepad(); // <-- This is where I want to construct the Gamepad
        simulatedGamepad.axes = mapping.axes;
        const buttonEvent = new GamepadEvent("gamepadbuttondown", {
            bubbles: true,
            cancelable: true,
            gamepad: simulatedGamepad,
        });
        document.dispatchEvent(buttonEvent);
    }
}

Solution

  • This isn't possible because the Gamepad API specification doesn't define a constructor for interface Gamepad:

    https://w3c.github.io/gamepad/#gamepad-interface

    Exposing an interface for creating simulated gamepads seems useful. If you want to pursue this please file a spec issue and we can continue the conversation there.

    https://github.com/w3c/gamepad/issues


    I think in your app it's not necessary to create a real Gamepad object. Just create a new Object() and set axes, buttons, and any other attributes your app expects.