Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Hacky gamepad controls for Dungeon Decorator
var gamepadPoller = -1;
function pollGamepad() {
var gamepads = navigator.getGamepads();
// Use input from any gamepad.
for (var i=0; i<gamepads.length; i++) {
if (gamepads[i]) {
var g = gamepads[i];
// Use any button for jump.
keyPressed[32] = Array.prototype.some.call(g.buttons, function(b) {return b.pressed; });
// Assume axis 0 is left/right, 1 is up/down. Not 100% reliable!
var DEADZONE = 0.25;
keyPressed[left] = g.axes[0] < -DEADZONE;
keyPressed[right] = g.axes[0] > DEADZONE;
keyPressed[up] = g.axes[1] < -DEADZONE;
keyPressed[down] = g.axes[1] > DEADZONE;
}
}
}
addEventListener("gamepadconnected", function() {
console.log('gamepad connected');
if (gamepadPoller == -1)
gamepadPoller = setInterval(pollGamepad, 15);
});
addEventListener("gamepaddisconnected", function() {
console.log('gamepad disconnected');
if (gamepadPoller != -1 && !Array.prototype.some.call(navigator.getGamepads(), function(g) {return g != undefined; })) {
clearInterval(gamepadPoller);
gamepadPoller = -1;
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment