Easy Keyboard Controls JavaScript
const Key = {
LEFT: 37,
UP: 38,
RIGHT: 39,
DOWN: 40,
disabled: false
}
const keyDown = {}
function setupKeys() {
const alph = 'abcdefghijklmnopqrstuvwxyz'.split('')
const keys = {}
const aKey = 65
alph.forEach((letter, i) => {
const idx = aKey + i
keyDown[idx] = false
Key[letter.toUpperCase()] = idx
})
document.addEventListener('keydown', e => {
if (!Key.disabled) {
keyDown[e.which] = true
}
})
document.addEventListener('keyup', e => {
keyDown[e.which] = false
})
}
setupKeys()
// later:
function loop() {
if (keyDown[Key.LEFT]) {
console.log('left')
}
if (keyDown[Key.UP]) {
console.log('up')
}
if (keyDown[Key.C] || keyDown[Key.D]) {
console.log('c or d key')
}
requestAnimationFrame(loop)
}
loop()
const info = document.createElement('div')
info.innerHTML = 'click to give focus - then use C, D or LEFT keys.'
document.body.appendChild(info)
Use a desktop and go into fullscreen when using the quick editor to see this in action…
This is a good way to deal with more complex key controls. event.which
and event.key
often won’t cut it, especially with key combos and different systems.