Last active
December 25, 2022 04:49
-
-
Save philldev/d5880a11e0b4251d9d7b225cf875ed35 to your computer and use it in GitHub Desktop.
Keyboard Input Typescript
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
type KeyboardState = 'pressed' | 'down' | 'released' | 'up' | |
class Keyboard { | |
private _keys: Record<string, KeyboardState> = {} | |
constructor(keys: string[]) { | |
for (const _key of keys) { | |
this._keys[_key] = 'up' | |
} | |
} | |
onPress(key: string) { | |
if (this._keys[key] === 'up') { | |
this._keys[key] = 'pressed' | |
} | |
} | |
onRelease(key: string) { | |
if (this._keys[key] === 'down') { | |
this._keys[key] = 'released' | |
} | |
} | |
wasPressed(key: string) { | |
return this._keys[key] === 'pressed' | |
} | |
wasReleased(key: string) { | |
return this._keys[key] === 'released' | |
} | |
isDown(key: string) { | |
return this._keys[key] === 'down' | |
} | |
isUp(key: string) { | |
return this._keys[key] === 'up' | |
} | |
update() { | |
for (const key in this._keys) { | |
if (Object.prototype.hasOwnProperty.call(this._keys, key)) { | |
const _key = this._keys[key] | |
if (_key === 'pressed') this._keys[key] = 'down' | |
if (_key === 'released') this._keys[key] = 'up' | |
} | |
} | |
} | |
} | |
const keyboard = new Keyboard(['a', 'd', 'w']) | |
window.addEventListener('keydown', (e) => { | |
keyboard.onPress(e.key) | |
}) | |
window.addEventListener('keyup', (e) => { | |
keyboard.onRelease(e.key) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment