diff --git a/src/game.js b/src/game.js index 09685fa..c52319b 100644 --- a/src/game.js +++ b/src/game.js @@ -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() { diff --git a/src/input.js b/src/input.js new file mode 100644 index 0000000..b21068e --- /dev/null +++ b/src/input.js @@ -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] + } +}