summaryrefslogtreecommitdiff
path: root/engine/systems/Render.ts
diff options
context:
space:
mode:
Diffstat (limited to 'engine/systems/Render.ts')
-rw-r--r--engine/systems/Render.ts55
1 files changed, 55 insertions, 0 deletions
diff --git a/engine/systems/Render.ts b/engine/systems/Render.ts
new file mode 100644
index 0000000..b5479e1
--- /dev/null
+++ b/engine/systems/Render.ts
@@ -0,0 +1,55 @@
+import { System, SystemNames } from ".";
+import { BoundingBox, ComponentNames, Sprite } from "../components";
+import type { Entity } from "../entities";
+import { Game } from "../Game";
+import type { DrawArgs } from "../interfaces";
+import { clamp } from "../utils";
+
+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.componentEntities.get(ComponentNames.Sprite)?.forEach((entityId) => {
+ const entity = game.entities.get(entityId);
+ const sprite = entity.getComponent<Sprite>(ComponentNames.Sprite);
+ sprite.update(dt);
+
+ let drawArgs: DrawArgs;
+ if (entity.hasComponent(ComponentNames.BoundingBox)) {
+ 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;
+ }
+
+ drawArgs = {
+ center: boundingBox.center,
+ dimension: boundingBox.dimension,
+ rotation: boundingBox.rotation,
+ };
+ }
+ sprite.draw(this.ctx, drawArgs);
+ });
+ }
+}