summaryrefslogtreecommitdiff
path: root/engine/systems/FacingDirection.ts
blob: daf639fb05f317b255522ab19087650cf0f16eb6 (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
import {
  ComponentNames,
  Velocity,
  FacingDirection as FacingDirectionComponent,
  Control,
} from "../components";
import { Game } from "../Game";
import { System, SystemNames } from "./";

export class FacingDirection extends System {
  constructor() {
    super(SystemNames.FacingDirection);
  }

  public update(_dt: number, game: Game) {
    game.forEachEntityWithComponent(
      ComponentNames.FacingDirection,
      (entity) => {
        if (!entity.hasComponent(ComponentNames.Velocity)) {
          return;
        }

        const totalVelocityComponent = new Velocity();
        const control = entity.getComponent<Control>(ComponentNames.Control);
        const velocity = entity.getComponent<Velocity>(
          ComponentNames.Velocity,
        ).velocity;

        totalVelocityComponent.add(velocity);
        if (control) {
          totalVelocityComponent.add(control.controlVelocityComponent.velocity);
        }

        const facingDirection = entity.getComponent<FacingDirectionComponent>(
          ComponentNames.FacingDirection,
        );

        if (totalVelocityComponent.velocity.dCartesian.dx > 0) {
          entity.addComponent(facingDirection.facingRightSprite);
        } else if (totalVelocityComponent.velocity.dCartesian.dx < 0) {
          entity.addComponent(facingDirection.facingLeftSprite);
        }
      },
    );
  }
}