Add input

This commit is contained in:
Bill Rossi 2025-06-02 18:54:00 -04:00
parent aa59cd0e92
commit daed360cdf
2 changed files with 40 additions and 0 deletions

View File

@ -1,4 +1,5 @@
import Dvd from "./dvd.js"
import Input from "./input.js"
export default class Game {
constructor(canvas) {
@ -7,6 +8,8 @@ export default class Game {
this.timestamp = 0
this.actors = []
this.actors.push(new Dvd(this, 200, 200))
this.input = new Input().initialize()
}
start() {
@ -24,6 +27,12 @@ export default class Game {
tick(dt) {
this.actors.forEach(actor => actor.tick(dt))
if (this.input.isInputPressed("attack")) console.log("attack!")
if (this.input.isInputPressed("interact")) console.log("interact!")
if (this.input.isInputPressed("up")) console.log("up!")
if (this.input.isInputPressed("down")) console.log("down!")
if (this.input.isInputPressed("left")) console.log("left!")
if (this.input.isInputPressed("right")) console.log("right!")
}
draw() {

31
src/input.js Normal file
View File

@ -0,0 +1,31 @@
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)
console.log(this)
return this
}
isInputPressed(inputName) {
return !!this.inputPressed[inputName]
}
keyFromInput(input) {
return this.keysToInputs[input]
}
}