@basementuniverse/scene-graph
v0.0.1
Published
A component for managing a graph of actors in a game scene
Readme
Game Component: Scene Graph
A basic scene graph component for use in 2d games.
Installation
npm install @basementuniverse/scene-graphHow to use
Create specialized nodes by extending SceneNode:
import { SceneNode } from '@basementuniverse/scene-graph';
class SpriteNode extends SceneNode {
sprite: Sprite;
override draw(ctx: CanvasRenderingContext2D): void {
if (!this.visible) {
return;
}
ctx.save();
ctx.setTransform(this.worldTransform.getMatrix());
this.sprite.draw(ctx);
ctx.restore();
for (const child of this.children) {
child.draw(ctx);
}
}
}Update and draw the scene graph in your game loop:
// Root of the graph
const root = new SceneNode();
// Add game objects
const player = new SpriteNode(...);
const weapon = new SpriteNode(...);
player.addChild(weapon);
root.addChild(player);
// Game loop
function update(dt: number) {
root.update(dt); // recursively calls update on all children
}
function draw(ctx: CanvasRenderingContext2D) {
root.updateWorldTransform(); // must happen before drawing
root.draw(ctx);
}