summaryrefslogtreecommitdiff
path: root/src/engine/systems/GridSpawner.ts
blob: c566444af10f2b3e2d844d05ee7de703d16d64af (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
import { System, SystemNames } from ".";
import { Game } from "..";
import { ComponentNames, Grid, GridSpawn } from "../components";
import { Direction } from "../interfaces";

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

  public update(_dt: number, game: Game) {
    game.forEachEntityWithComponent(ComponentNames.GridSpawn, (entity) => {
      const spawn = entity.getComponent<GridSpawn>(ComponentNames.GridSpawn)!;
      const hasGrid = entity.hasComponent(SystemNames.Grid);

      if (spawn.direction === Direction.NONE || !hasGrid) {
        return;
      }

      const grid = entity.getComponent<Grid>(SystemNames.Grid)!;

      const direction = spawn.direction;
      const spawned = spawn.spawner();
      if (!spawned) {
        return;
      }
      spawn.direction = Direction.NONE;
      entity.addComponent(spawn);

      const spawnedGrid = spawned.getComponent<Grid>(SystemNames.Grid)!;
      spawnedGrid.gridPosition = grid.gridPosition;
      spawnedGrid.movingDirection = direction;
      spawned.addComponent(spawnedGrid);

      game.addEntity(spawned);
      entity.addComponent(spawned);
    });
  }
}