48 lines
1.2 KiB
TypeScript
48 lines
1.2 KiB
TypeScript
export class KeyboardInput {
|
|
private readonly pressed = new Set<string>()
|
|
private readonly justPressed = new Set<string>()
|
|
|
|
private readonly onKeyDown = (event: KeyboardEvent) => {
|
|
if (!this.pressed.has(event.code)) {
|
|
this.justPressed.add(event.code)
|
|
}
|
|
this.pressed.add(event.code)
|
|
}
|
|
|
|
private readonly onKeyUp = (event: KeyboardEvent) => {
|
|
this.pressed.delete(event.code)
|
|
}
|
|
|
|
start() {
|
|
window.addEventListener('keydown', this.onKeyDown)
|
|
window.addEventListener('keyup', this.onKeyUp)
|
|
}
|
|
|
|
stop() {
|
|
window.removeEventListener('keydown', this.onKeyDown)
|
|
window.removeEventListener('keyup', this.onKeyUp)
|
|
this.pressed.clear()
|
|
this.justPressed.clear()
|
|
}
|
|
|
|
getMoveAxis() {
|
|
let x = 0
|
|
let z = 0
|
|
|
|
if (this.pressed.has('KeyW') || this.pressed.has('ArrowUp')) z -= 1
|
|
if (this.pressed.has('KeyS') || this.pressed.has('ArrowDown')) z += 1
|
|
if (this.pressed.has('KeyA') || this.pressed.has('ArrowLeft')) x -= 1
|
|
if (this.pressed.has('KeyD') || this.pressed.has('ArrowRight')) x += 1
|
|
|
|
return { x, z }
|
|
}
|
|
|
|
consumePressed(code: string) {
|
|
const hit = this.justPressed.has(code)
|
|
if (hit) {
|
|
this.justPressed.delete(code)
|
|
}
|
|
return hit
|
|
}
|
|
}
|