summaryrefslogtreecommitdiff
path: root/engine/systems/Input.ts
blob: eefb3346d1d8fb7890bb14b969a136d30305edb5 (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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
import {
  Jump,
  Forces,
  Acceleration,
  ComponentNames,
  Velocity,
  Mass,
} from "../components";
import { Game } from "../Game";
import { KeyConstants, PhysicsConstants } from "../config";
import type { Entity } from "../entities";
import { Action } from "../interfaces";
import { System, SystemNames } from "./";

/**
 * TODO: Make velocities reset on each game loop (as similar to acceleration)
 */
export class Input extends System {
  private keys: Set<string>;
  private actionTimeStamps: Map<Action, number>;

  constructor() {
    super(SystemNames.Input);

    this.keys = new Set<number>();
    this.actionTimeStamps = new Map<Action, number>();
  }

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

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

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

  public update(dt: number, game: Game) {
    game.componentEntities.get(ComponentNames.Control)?.forEach((entityId) => {
      const entity = game.entities.get(entityId);
      if (!entity.hasComponent(ComponentNames.Velocity)) {
        return;
      }

      const velocity = entity.getComponent<Velocity>(ComponentNames.Velocity);

      if (this.hasSomeKey(KeyConstants.ActionKeys.get(Action.MOVE_RIGHT))) {
        velocity.dCartesian.dx = PhysicsConstants.PLAYER_MOVE_VEL;
      } else if (
        this.hasSomeKey(KeyConstants.ActionKeys.get(Action.MOVE_LEFT))
      ) {
        velocity.dCartesian.dx = -PhysicsConstants.PLAYER_MOVE_VEL;
      } else {
        velocity.dCartesian.dx = 0;
      }
    });

    game.componentEntities.get(ComponentNames.Jump)?.forEach((entityId) => {
      const entity = game.entities.get(entityId);
      const jump = entity.getComponent<Jump>(ComponentNames.Jump);
      const velocity = entity.getComponent<Velocity>(ComponentNames.Velocity);

      if (this.hasSomeKey(KeyConstants.ActionKeys.get(Action.JUMP))) {
        if (jump.canJump) {
          this.actionTimeStamps.set(Action.JUMP, performance.now());

          velocity.dCartesian.dy = PhysicsConstants.PLAYER_JUMP_INITIAL_VEL;
          jump.canJump = false;
        }

        if (
          performance.now() - this.actionTimeStamps.get(Action.JUMP) <
          PhysicsConstants.MAX_JUMP_TIME_MS
        ) {
          const mass = entity.getComponent<Mass>(ComponentNames.Mass).mass;
          entity.getComponent<Forces>(ComponentNames.Forces)?.forces.push({
            fCartesian: { fy: mass * PhysicsConstants.PLAYER_JUMP_ACC },
          });
        }
      }
    });
  }
}