summaryrefslogtreecommitdiff
path: root/src/engine/systems/Input.ts
blob: 9b88378c43a3948e62305403c1f0a8aef242d321 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
import { SystemNames, System } from ".";
import { Game } from "..";
import { ComponentNames } from "../components";
import { Control } from "../components/Control";
import { Action, KeyConstants } from "../config";
import { Entity } from "../entities";
import { Coord2D } from "../interfaces";

export class Input extends System {
  private keys: Set<string>;
  private mousePosition: Coord2D;

  constructor() {
    super(SystemNames.Input);

    this.keys = new Set();
    this.mousePosition = { x: 0, y: 0 };
  }

  public clearKeys() {
    this.keys.clear();
  }

  public keyPressed(key: string) {
    this.keys.add(key);
  }

  public keyReleased(key: string) {
    this.keys.delete(key);
  }

  public update(_dt: number, game: Game) {
    game.forEachEntityWithComponent(ComponentNames.Control, (entity) =>
      this.handleInput(entity),
    );
  }

  public handleInput(entity: Entity) {
    const controlComponent = entity.getComponent<Control>(
      ComponentNames.Control,
    );
    if (!controlComponent.isControllable) return;

    if (this.hasSomeKey(KeyConstants.ActionKeys.get(Action.INTERACT))) {
      console.log("interact");
    }
  }

  private hasSomeKey(keys?: string[]): boolean {
    if (keys) {
      return keys.some((key) => this.keys.has(key));
    }
    return false;
  }

  public setMousePosition(mousePosition: Coord2D) {
    this.mousePosition = mousePosition;
  }

  public getMousePosition(): Coord2D {
    return this.mousePosition;
  }
}