initial commit

This commit is contained in:
Gregg Tavares 2019-02-22 14:57:35 +09:00
commit d0da90a25e

81
index.html Normal file
View File

@ -0,0 +1,81 @@
<body>
<h1>HTML5 Gamepad Test</h1>
<div id="running"></div>
<div id="gamepads"></div>
</body>
<script>
const runningElem = document.querySelector('#running');
const gamepadsElem = document.querySelector('#gamepads');
const gamepadsByIndex = {};
function addGamepad(gamepad) {
console.log('add:', gamepad.index);
const elem = document.createElement('pre');
gamepadsElem.appendChild(elem);
gamepadsByIndex[gamepad.index] = {
gamepad,
elem,
};
}
function removeGamepad(gamepad) {
const info = gamepadsByIndex[gamepad.index];
if (info) {
delete gamepadsByIndex[gamepad.index];
info.elem.parentElement.removeChild(info.elem);
}
}
function addGamepadIfNew(gamepad) {
if (!gamepadsByIndex[gamepad.index]) {
addGamepad(gamepad);
}
}
function handleConnect(e) {
console.log('connect');
addGamepadIfNew(e.gamepad);
}
function handleDisconnect(e) {
console.log('disconnect');
removeGamepad(e.gamepad);
}
const keys = ['connected', 'displayId', 'mapping', /*'timestamp'*/];
function processController(info) {
const {elem, gamepad} = info;
const lines = [`gamepad:${gamepad.index}`];
for (const key of keys) {
lines.push(`${key}: ${gamepad[key]}`);
}
lines.push(gamepad.axes.map((v, ndx) => `${ndx}: ${v.toFixed(2)}`).join(','));
lines.push(gamepad.buttons.map((v, ndx) => `${ndx}: ${v.pressed}, ${v.value.toFixed(2)}`).join(','));
elem.textContent = lines.join('\n');
}
function addNewPads() {
const gamepads = navigator.getGamepads();
for (let i = 0; i < gamepads.length; i++) {
const gamepad = gamepads[i]
if (gamepad) {
addGamepadIfNew(gamepad);
}
}
}
window.addEventListener("gamepadconnected", handleConnect);
window.addEventListener("gamepaddisconnected", handleDisconnect);
function process() {
runningElem.textContent = ((performance.now() * 0.001 * 60 | 0) % 100).toString().padStart(2, '0');
addNewPads(); // some browsers add by polling, others by event
Object.values(gamepadsByIndex).forEach(processController);
requestAnimationFrame(process);
}
requestAnimationFrame(process);
</script>