4

I'm attempting to get the browser to report the status of my XBOX controller. However, it appears to become "stuck" after the first button press. What am I doing wrong?

<body>
    <script>
        var gamepad = false;
        var gamepadDIV = []

        window.addEventListener("gamepadconnected", function(e) {
            gamepad = e.gamepad;

            for (i = 0; i < gamepad.buttons.length + gamepad.axes.length; i++) {
                gamepadDIV.push(document.createElement('div'));
                document.body.appendChild(gamepadDIV[i]);
            }

        });

        window.addEventListener("gamepaddisconnected", function() {
            gamepad = false;
        });


        function animation() {

            if (gamepad != false) {

                for (i = 0; i < gamepad.buttons.length; i++) {
                    gamepadDIV[i].innerHTML = gamepad.buttons[i].pressed;
                }

                for (i = gamepad.buttons.length; i < gamepad.buttons.length + gamepad.axes.length; i++) {
                    gamepadDIV[i].innerHTML = gamepad.axes[i - gamepad.buttons.length].value;
                }

            }

            window.requestAnimationFrame(animation);
        }
        animation();

    </script>
</body>
Daniel Foreman
  • 105
  • 2
  • 6
  • Code works fine for me as-is: https://jsfiddle.net/khrismuc/rnz5f6vg/ –  May 25 '20 at 10:23
  • Are you using FireFox? Because I just tested it in there, and like you said it works fine. Using Chrome or the latest Microsoft Edge however, it sticks on the first button and never changes. Are you having the same issue, or is it unique to my setup? – Daniel Foreman May 25 '20 at 13:28
  • You're right, it doesn't work in Chrome at all. –  May 25 '20 at 16:06

1 Answers1

4

I ran into the same issue with Chrome too.

Basically Chrome doesn't update the Gamepad object as state changes. Instead you have to poll it for updated state.

In one of the tutorials on MDN you'll see this this line:

var gamepads = navigator.getGamepads 
    ? navigator.getGamepads() 
    : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads : [])

So basically as I understand it, you can use the gamepadconnected event to handle initialization logic but after that you can't reference the object directly to get state changes.

You can find more about that here: https://developer.mozilla.org/en-US/docs/Web/API/Gamepad_API/Using_the_Gamepad_API

Dan Fletcher
  • 1,099
  • 11
  • 29