top-down-action-adventure/src/input.js

31 lines
820 B
JavaScript
Raw Normal View History

2025-06-02 18:54:00 -04:00
export default class Input {
constructor() {
this.keysToInputs = {
ArrowUp: "up",
ArrowDown: "down",
ArrowLeft: "left",
ArrowRight: "right",
x: "attack",
z: "interact"
}
this.inputsToKeys = Object.fromEntries(Object.keys(this.keysToInputs).map(key => [this.keysToInputs[key], key]))
this.inputPressed = Object.fromEntries(Object.keys(this.inputsToKeys).map(key => [key, false]))
}
initialize() {
window.addEventListener("keydown", key => this.inputPressed[this.keyFromInput(key.key)] = true)
window.addEventListener("keyup", key => this.inputPressed[this.keyFromInput(key.key)] = false)
return this
}
isInputPressed(inputName) {
return !!this.inputPressed[inputName]
}
keyFromInput(input) {
return this.keysToInputs[input]
}
}