Skip to content

Instantly share code, notes, and snippets.

@tex2e
Created September 28, 2017 03:15
Show Gist options
  • Save tex2e/46ee59a92fdbdb6de7fcb54ae62a561c to your computer and use it in GitHub Desktop.
Save tex2e/46ee59a92fdbdb6de7fcb54ae62a561c to your computer and use it in GitHub Desktop.
Using all gamepad button infomation
'use strict';
window.addEventListener("gamepadconnected", function(e) {
var gp = e.gamepad;
console.log("gamepad" + gp.index + " is connected!");
}, false);
window.addEventListener("gamepaddisconnected", function(e) {
var gp = e.gamepad;
console.log("gamepad" + gp.index + " is disconnected!");
}, false);
function buttonPressed(b) {
if (typeof(b) == "object") {
return b.pressed;
}
return b == 1.0;
}
function gameLoop() {
requestAnimationFrame(gameLoop);
var gamepads = navigator.getGamepads ? navigator.getGamepads()
: navigator.webkitGetGamepads ? navigator.webkitGetGamepads
: [];
if (!gamepads) return;
if (gamepads.length < 1) return;
for (var i = 0; i < gamepads.length; i++) {
var gp = gamepads[i];
var result = "" + gp.index;
if (buttonPressed(gp.buttons[0])) {
result += " [press 0]";
} else if (buttonPressed(gp.buttons[2])) {
result += " [press 2]";
}
if (buttonPressed(gp.buttons[1])) {
result += " [press 1]";
} else if (buttonPressed(gp.buttons[3])) {
result += " [press 3]";
}
var x_axis = gp.axes[0].toFixed(4);
var y_axis = gp.axes[1].toFixed(4);
result += " (" + x_axis + ", " + y_axis + ")";
console.log(result);
}
}
gameLoop();
@tex2e
Copy link
Author

tex2e commented Sep 28, 2017

Ubuntu: apt-get install joystick

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment