aboutsummaryrefslogtreecommitdiff
path: root/static/src/engine/render.ts
blob: 8f0343a8fe1ce709ec586cb43aa2de30055a5b7d (plain) (blame)
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 {
  ComponentType,
  PositionComponent,
  TrailingPositionComponent,
} from "./component";
import { Game } from "./game";
import { System, SystemType } from "./system";
import { drawLaserPen } from "laser-pen";

export class RenderSystem extends System {
  constructor(private readonly canvas: HTMLCanvasElement) {
    super(SystemType.RENDER);
  }

  public set_world_dimensions(width: number, height: number) {
    this.canvas.width = width;
    this.canvas.height = height;
  }

  public update(_dt: number, game: Game) {
    const ctx = this.canvas.getContext("2d");
    if (ctx === null) return;
    ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);

    game.for_each_entity_with_component(ComponentType.RENDERABLE, (entity) => {
      if (ComponentType.TRAILING_POSITION in entity.components) {
        const trailing_position = entity.components[
          ComponentType.TRAILING_POSITION
        ] as TrailingPositionComponent;
        if (trailing_position.trails.length < 3) return;
        drawLaserPen(ctx, trailing_position.trails);
        return;
      }

      if (ComponentType.POSITION in entity.components) {
        const position = entity.components[
          ComponentType.POSITION
        ] as PositionComponent;
        ctx.beginPath();
        ctx.arc(position.x, position.y, 50, 0, 2 * Math.PI);
        ctx.stroke();
        return;
      }
    });
  }
}