Skip to content

Instantly share code, notes, and snippets.

@duhaime
Created February 10, 2018 20:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save duhaime/89a7c84dcb23b8f5a1107c6880c90853 to your computer and use it in GitHub Desktop.
Save duhaime/89a7c84dcb23b8f5a1107c6880c90853 to your computer and use it in GitHub Desktop.
Buffalo Controller
(function() {
/**
* Buffalo Classic USB Gamepad button ids:
* 0: B (yellow)
* 1: A (red)
* 2: Y (green)
* 3: X (blue)
* 4,6: left trigger (top left)
* 5,7: right trigger (top right)
* 4,6: left trigger (top left)
* 5,7: right trigger (top right)
* 8: select
* 9: start
*
*
* 12: up (d-pad)
* 13: down (d-pad)
* 14: left (d-pad)
* 15: right (d-pad)
**/
/**
* Request animation frame polyfill
**/
var lastTime = 0;
var vendors = ['ms', 'moz', 'webkit', 'o'];
for (var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame'];
window.cancelAnimationFrame = window[vendors[x]+'CancelAnimationFrame'] ||
window[vendors[x]+'CancelRequestAnimationFrame'];
}
if (!window.requestAnimationFrame)
window.requestAnimationFrame = function(callback, element) {
var currTime = new Date().getTime();
var timeToCall = Math.max(0, 16 - (currTime - lastTime));
var id = window.setTimeout(function() {
callback(currTime + timeToCall);
}, timeToCall);
lastTime = currTime + timeToCall;
return id;
};
if (!window.cancelAnimationFrame)
window.cancelAnimationFrame = function(id) { clearTimeout(id); };
/**
* Gamepads
**/
function onConnect(e) {
console.log('Gamepad connected at index %d: %s. %d buttons, %d axes.',
e.gamepad.index, e.gamepad.id,
e.gamepad.buttons.length, e.gamepad.axes.length);
gamepadIndices.push(e.gamepad.index);
}
function onDisconnect(e) {
console.log('Gamepad disconnected from index %d: %s',
e.gamepad.index, e.gamepad.id);
}
function getGamepads() {
return navigator.getGamepads();
}
function getPressedButtons(gamepad) {
return gamepad.buttons.reduce(function(arr, obj, idx) {
if (obj.pressed) arr.push(idx);
return arr;
}, [])
}
function render() {
gamepads = getGamepads();
gamepadIndices.forEach(function(i) {
var pressed = getPressedButtons(gamepads[i]);
if (pressed.length) console.log(pressed)
})
requestAnimationFrame(render);
}
var gamepadIndices = [];
window.addEventListener('gamepadconnected', onConnect);
window.addEventListener('gamepaddisconnected', onDisconnect);
render()
})()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment