Created
February 10, 2018 20:28
-
-
Save duhaime/89a7c84dcb23b8f5a1107c6880c90853 to your computer and use it in GitHub Desktop.
Buffalo Controller
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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