HTML Gamepad API

Date: 2018-10-25
<script>
const document = window.document;
const navigator = window.navigator;

let gamePadSelect = null;
let axisSelect = null;

let init = function () {
    gamePadSelect = $('<select>');
    axisSelect = $('<select>');
    $('body')
        .append(gamePadSelect);
    $('body')
        .append(axisSelect);

    updateGamepads();
};

let updateGamepads = function () {
    let gamepads = navigator.getGamepads();

    for (let i = 0; i < gamepads.length; i += 1) {
        let pad = gamepads[i];
        if (pad) {
            let option = $('<option>');
            option.attr('value', i);
            option.text(pad.id);
            gamePadSelect.append(option);

            for (let j = 0; j < pad.axes.length; j += 1) {
                let option2 = $('<option>');
                option2.attr('value', j);
                option2.text('Axis ' + j);
                axisSelect.append(option2);
            }
        }
    }
    console.log(gamepads);
};

$(document).ready(init);

window.addEventListener('gamepadconnected', updateGamepads);
window.addEventListener('gamepaddisconnected', updateGamepads);

/*
interface Gamepad {
    readonly        attribute DOMString           id;
    readonly        attribute long                index;
    readonly        attribute boolean             connected;
    readonly        attribute DOMHighResTimeStamp timestamp;
    readonly        attribute GamepadMappingType  mapping;
    readonly        attribute double[]            axes;
    readonly        attribute GamepadButton[]     buttons;
};
interface GamepadButton {
    readonly        attribute boolean pressed;
    readonly        attribute double  value;
};
partial interface Navigator {
    sequence<Gamepad?> getGamepads ();
};
window.addEventListener('gamepadconnected', fn);
window.addEventListener('gamepaddisconnected', fn);
navigator.getGamepads()
navigator.webkitGetGamepads()
*/

// shim layer with setTimeout fallback
let requestAnimFrame = (function () {
    return window.requestAnimationFrame ||
        window.webkitRequestAnimationFrame ||
        window.mozRequestAnimationFrame ||
        function (callback) {
            window.setTimeout(callback, 1000 / 60);
        };
})();

// gamepads should look like [null, [object Gamepad]]
let prevVal = 0;
function runAnimation() {
    requestAnimFrame(runAnimation);
    let gamepads = navigator.getGamepads();
    for (let i = 0; i < gamepads.length; i += 1) {
        let pad = gamepads[i];
        if (pad) {
            if (i == gamePadSelect.val()) {

                let val = pad.axes[axisSelect.val()];
                if (val !== prevVal) {
                    prevVal = val;
                    console.log(val);
                    socket.emit('axes', JSON.stringify({x: val}));
                }
            }
        }
    }
}

requestAnimFrame(runAnimation);
</script>

 

15590cookie-checkHTML Gamepad API