jumpstorm/engine/systems/Render.ts

51 lines
1.4 KiB
TypeScript
Raw Normal View History

2023-08-25 18:48:17 -04:00
import { System, SystemNames } from '.';
import { BoundingBox, ComponentNames, Sprite } from '../components';
import { Game } from '../Game';
import { clamp } from '../utils';
2023-07-19 23:38:24 -04:00
export class Render extends System {
private ctx: CanvasRenderingContext2D;
constructor(ctx: CanvasRenderingContext2D) {
super(SystemNames.Render);
this.ctx = ctx;
}
public update(dt: number, game: Game) {
2023-07-19 23:38:24 -04:00
this.ctx.clearRect(0, 0, this.ctx.canvas.width, this.ctx.canvas.height);
2023-08-12 15:49:16 -04:00
game.forEachEntityWithComponent(ComponentNames.Sprite, (entity) => {
2023-07-19 23:38:24 -04:00
const sprite = entity.getComponent<Sprite>(ComponentNames.Sprite);
sprite.update(dt);
2023-08-12 15:49:16 -04:00
const boundingBox = entity.getComponent<BoundingBox>(
2023-08-25 18:48:17 -04:00
ComponentNames.BoundingBox
2023-08-12 15:49:16 -04:00
);
// don't render if we're outside the screen
if (
clamp(
boundingBox.center.y,
-boundingBox.dimension.height / 2,
2023-08-25 18:48:17 -04:00
this.ctx.canvas.height + boundingBox.dimension.height / 2
2023-08-12 15:49:16 -04:00
) != boundingBox.center.y ||
clamp(
boundingBox.center.x,
-boundingBox.dimension.width / 2,
2023-08-25 18:48:17 -04:00
this.ctx.canvas.width + boundingBox.dimension.width / 2
2023-08-12 15:49:16 -04:00
) != boundingBox.center.x
) {
return;
2023-07-19 23:38:24 -04:00
}
2023-08-12 15:49:16 -04:00
const drawArgs = {
center: boundingBox.center,
dimension: boundingBox.dimension,
2023-08-25 18:48:17 -04:00
rotation: boundingBox.rotation
2023-08-12 15:49:16 -04:00
};
2023-07-19 23:38:24 -04:00
sprite.draw(this.ctx, drawArgs);
});
}
}