Last active
August 16, 2020 17:35
-
-
Save nbarkhina/0f1eee55401070285a5af881d7498396 to your computer and use it in GitHub Desktop.
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
allButtons = []; | |
gamepadFound = false; | |
function initGamePad(e) { | |
var gp = e.gamepad; | |
if (gp.buttons.length > 0 && !gamepadFound){ | |
for(let i=0;i<gp.buttons.length;i++){ | |
gamepadFound = true; | |
allButtons.push( | |
{ | |
pressed:false, | |
index:i | |
} | |
); | |
} | |
gamepadAnimationLoop(); | |
} | |
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); | |
} | |
function gamepadAnimationLoop(){ | |
window.requestAnimationFrame(gamepadAnimationLoop); | |
processGamepad(); | |
} | |
function setupGamePad() { | |
window.addEventListener("gamepadconnected", initGamePad); | |
} | |
//call this function once every frame | |
function processGamepad() { | |
try { | |
var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads : []); | |
if (!gamepads) | |
return; | |
var gp = null; | |
for (let i = 0; i < gamepads.length; i++) { | |
if (gamepads[i] && gamepads[i].buttons.length > 0) | |
gp = gamepads[i]; | |
} | |
if (gp) { | |
for(let i=0;i<gp.buttons.length;i++){ | |
let button = gp.buttons[i]; | |
if (button.pressed && !allButtons[i].pressed){ | |
allButtons[i].pressed = true; | |
let charcode = String.fromCharCode(65 + i); | |
console.log('Sending Key: ' + charcode); | |
//send this keyboard event to your keydown listener | |
let keyEvent = new KeyboardEvent('keydown', { key: charcode, keyCode: (65+i),bubbles:true }); | |
document.activeElement.dispatchEvent(keyEvent); | |
} | |
if (!button.pressed && allButtons[i].pressed){ | |
allButtons[i].pressed = false; | |
let charcode = String.fromCharCode(65 + i); | |
console.log('Releasing Key: ' + charcode); | |
//send this keyboard event to your keyup listener | |
let keyEvent = new KeyboardEvent('keyup', { key: charcode, keyCode: (65+i),bubbles:true }); | |
document.activeElement.dispatchEvent(keyEvent); | |
} | |
} | |
} | |
} | |
catch (error) { } | |
} | |
setupGamePad(); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment