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
69
70
71
72
|
import { System, SystemNames } from ".";
import {
BoundingBox,
Text,
ComponentNames,
Highlight,
Renderable,
} from "../components";
import { Game } from "..";
import { clamp } from "../utils";
import { DrawArgs } from "../interfaces";
export class Render extends System {
private ctx: CanvasRenderingContext2D;
constructor(ctx: CanvasRenderingContext2D) {
super(SystemNames.Render);
this.ctx = ctx;
}
public update(dt: number, game: Game) {
this.ctx.clearRect(0, 0, this.ctx.canvas.width, this.ctx.canvas.height);
game.forEachEntityWithComponent(ComponentNames.Sprite, (entity) => {
const sprite = entity.getComponent<Renderable>(ComponentNames.Sprite);
sprite.update(dt);
const boundingBox = entity.getComponent<BoundingBox>(
ComponentNames.BoundingBox
);
// don't render if we're outside the screen
if (
clamp(
boundingBox.center.y,
-boundingBox.dimension.height / 2,
this.ctx.canvas.height + boundingBox.dimension.height / 2
) != boundingBox.center.y ||
clamp(
boundingBox.center.x,
-boundingBox.dimension.width / 2,
this.ctx.canvas.width + boundingBox.dimension.width / 2
) != boundingBox.center.x
) {
return;
}
const drawArgs: DrawArgs = {
center: boundingBox.center,
dimension: boundingBox.dimension,
rotation: boundingBox.rotation,
};
if (entity.hasComponent(ComponentNames.Highlight)) {
const highlight = entity.getComponent<Highlight>(
ComponentNames.Highlight
);
drawArgs.tint = highlight.isHighlighted ? "red" : undefined;
}
if (entity.hasComponent(ComponentNames.Text)) {
const text = entity.getComponent<Text>(ComponentNames.Text);
drawArgs.backgroundText = {
text: text.text,
font: text.font,
fillStyle: text.fillStyle,
textAlign: text.textAlign,
};
}
sprite.draw(this.ctx, drawArgs);
});
}
}
|