javascripthtmlgamepad-api

HTML5 Gamepad API TypeError


I'm trying to write some code to get a gamepad and list the axes' position:

window.addEventListener("gamepadconnected", (e) => {
                console.log("Gamepad connected at index %d: %s. %d buttons, %d axes.",
                    e.gamepad.index, e.gamepad.id,
                    e.gamepad.buttons.length, e.gamepad.axes.length);
            });
            const [gp] = navigator.getGamepads()[0]
            console.log(gp.axes)

and get an Uncaught TypeError: object null is not iterable (cannot read property Symbol(Symbol.iterator)) .
Would really appreciate help.


Solution

  • getGamepads returns sequence<Gamepad?>. You're using destructuring assignment syntax to unpack it into a variable.

    const [gp] = navigator.getGamepads()[0]
    

    This doesn't work because you're trying to unpack getGamepads()[0] which is a Gamepad object, not a sequence. Try this:

    const [gp] = navigator.getGamepads();
    

    If you don't want to use destructuring assignment syntax:

    const gp = navigator.getGamepads()[0];