2d-physics-engine
Version:
A lightweight, flexible 2D physics engine with ECS architecture, built with TypeScript
79 lines • 2.86 kB
JavaScript
import { Drawer } from '../components/DrawerComponents/Drawer.component';
import { Transform } from '../components/Transform.component';
import { Vector2 } from '../math/Vector2';
import { System } from './System.abstract';
export class Rendering extends System {
constructor(canvas, canvasCtx) {
super();
Object.defineProperty(this, "canvas", {
enumerable: true,
configurable: true,
writable: true,
value: canvas
});
Object.defineProperty(this, "canvasCtx", {
enumerable: true,
configurable: true,
writable: true,
value: canvasCtx
});
Object.defineProperty(this, "needsFixedUpdate", {
enumerable: true,
configurable: true,
writable: true,
value: false
});
Object.defineProperty(this, "spriteCache", {
enumerable: true,
configurable: true,
writable: true,
value: new Map()
});
}
/** Load a sprite into the cache for faster rendering. */
async loadSprite(key, imagePath) {
return new Promise((resolve, reject) => {
const img = new Image();
img.onload = () => {
this.spriteCache.set(key, img);
resolve();
};
img.onerror = () => reject(new Error(`Failed to load sprite: ${imagePath}`));
img.src = imagePath;
});
}
/** Draw a sprite at the given position with optional rotation and scale. */
drawSprite(key, position, rotation = 0, scale = new Vector2(1, 1)) {
const sprite = this.spriteCache.get(key);
if (!sprite)
return;
this.canvasCtx.save();
this.canvasCtx.translate(position.x, position.y);
this.canvasCtx.rotate(rotation);
this.canvasCtx.scale(scale.x, scale.y);
this.canvasCtx.drawImage(sprite, -sprite.width / 2, -sprite.height / 2);
this.canvasCtx.restore();
}
drawLineToPosition(transform) {
this.canvasCtx.beginPath();
this.canvasCtx.moveTo(0, 0);
this.canvasCtx.lineTo(transform.getPosition().x, transform.getPosition().y);
this.canvasCtx.strokeStyle = 'red';
this.canvasCtx.stroke();
}
// Clear the entire canvas
clear() {
this.canvasCtx.clearRect(0, 0, this.canvas.width, this.canvas.height);
}
update(_deltaTime, scene) {
this.clear();
for (const entity of scene.getEntities()) {
const drawer = entity.getComponent(Drawer);
const transform = entity.getComponent(Transform);
if (!transform || !drawer)
continue;
drawer.draw(this.canvasCtx, transform);
}
}
}
//# sourceMappingURL=Rendering.system.js.map