summaryrefslogtreecommitdiff
path: root/src/engine/systems/FacingDirection.ts
blob: ec73d5877f8751efa94ac6937771f48848f79b1a (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
import {
  ComponentNames,
  FacingDirection as FacingDirectionComponent,
  BoundingBox,
  Sprite,
} from "../components";
import { Game } from "../Game";
import { System, SystemNames, Input } from ".";
import { Direction, angleToDirection } from "../interfaces";

export class FacingDirection extends System {
  private input: Input;

  constructor(input: Input) {
    super(SystemNames.FacingDirection);

    this.input = input;
  }

  public update(_dt: number, game: Game) {
    const mousePosition = this.input.getMousePosition();
    const mouseBoundingBox = new BoundingBox(mousePosition, {
      width: 0,
      height: 0,
    });

    game.forEachEntityWithComponent(
      ComponentNames.FacingDirection,
      (entity) => {
        const facingDirection = entity.getComponent<FacingDirectionComponent>(
          ComponentNames.FacingDirection,
        );
        if (!entity.hasComponent(ComponentNames.Sprite)) {
          return;
        }

        if (entity.hasComponent(ComponentNames.Control)) {
          const boundingBox = entity.getComponent<BoundingBox>(
            ComponentNames.BoundingBox,
          )!;

          const { center } = boundingBox;
          const angle = Math.atan2(
            mousePosition.y - center.y,
            mousePosition.x - center.x,
          );

          const mouseInBoundingBox =
            boundingBox.isCollidingWith(mouseBoundingBox);
          const direction = mouseInBoundingBox
            ? Direction.NONE
            : angleToDirection(angle);

          facingDirection.setDirection(direction);
          entity.addComponent(facingDirection);
        }

        const oldSprite = entity.getComponent<Sprite>(ComponentNames.Sprite);
        const sprite = facingDirection.directionSprites.get(
          facingDirection.currentDirection,
        )!;
        sprite.fillTimingsFromSprite(oldSprite);

        entity.addComponent(sprite);
      },
    );
  }
}