summaryrefslogtreecommitdiff
path: root/src/engine/systems/FacingDirection.ts
blob: f831bf6045c663a33c330ab0913824bcdc0a9ec6 (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 {
  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) => {
        if (!entity.hasComponent(ComponentNames.BoundingBox)) {
          return;
        }

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

        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);

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

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