Skip to content

Instantly share code, notes, and snippets.

@hnaohiro
Last active August 29, 2015 13:57
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save hnaohiro/9525161 to your computer and use it in GitHub Desktop.
Save hnaohiro/9525161 to your computer and use it in GitHub Desktop.
var gamepad = null;
var timer = null;
window.addEventListener("gamepadconnected", function(e) {
if (!gamepad) {
gamepad = e.gamepad;
timer = setInterval('updateStatus()', 100);
}
});
window.addEventListener("gamepaddisconnected", function(e) {
gamepad = null;
clearInterval(timer);
});
function updateStatus() {
if (gamepad) {
var status = {
buttons: [],
axes: []
};
for (var i = 0; i < gamepad.buttons.length; i++) {
var button = gamepad.buttons[i];
var pressed = (button.pressed || button.value > 0);
status.buttons.push(pressed);
}
for (var i = 0; i < gamepad.axes.length; i++) {
var axes = gamepad.axes[i];
status.axes.push(axes.toFixed(4));
}
showStatus(status);
}
}
function showStatus(status) {
for (var i = 0; i < status.buttons.length; i++) {
var button = status.buttons[i];
if (button) {
console.log('button' + i + ' pressed');
}
}
for (var i = 0; i < status.axes.length; i++) {
var axes = status.axes[i];
console.log('axes' + i + ': ' + axes);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment