Daniel Foreman
Daniel Foreman

Reputation: 125

gamepad javascript failing to updated as expected

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>

Upvotes: 6

Views: 663

Answers (1)

Dan Fletcher
Dan Fletcher

Reputation: 1248

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

Upvotes: 6

Related Questions