Created
September 13, 2020 08:21
-
-
Save kayac-chang/861f6be2970f47eaccc6b0814a930ccf to your computer and use it in GitHub Desktop.
sync keyboard event to requestAnimationFrame
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
export function KeyBoard(keymap) { | |
const pressing = new Set(); | |
window.addEventListener("keydown", ({ key }) => | |
keymap[key] && pressing.add(keymap[key]) | |
); | |
window.addEventListener("keyup", ({ key }) => | |
keymap[key] && pressing.delete(keymap[key]) | |
); | |
return () => pressing; | |
} | |
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
import { KeyBoard } from './KeyBoard'; | |
const getAction = KeyBoard({ | |
w: 'Up', | |
s: 'Down', | |
a: 'Left', | |
d: 'Right', | |
}); | |
function loop() { | |
// get current press key | |
const pressing = getAction(); | |
// print out the key you press | |
console.log(pressing); | |
requestAnimationFrame(loop); | |
} | |
requestAnimationFrame(loop); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment