UNPKG

2d-physics-engine

Version:

A lightweight, flexible 2D physics engine with ECS architecture, built with TypeScript

90 lines 2.67 kB
export class Entity { constructor(name = 'Entity') { Object.defineProperty(this, "name", { enumerable: true, configurable: true, writable: true, value: name }); Object.defineProperty(this, "components", { enumerable: true, configurable: true, writable: true, value: new Map() }); Object.defineProperty(this, "children", { enumerable: true, configurable: true, writable: true, value: new Set() }); Object.defineProperty(this, "active", { enumerable: true, configurable: true, writable: true, value: true }); Object.defineProperty(this, "parent", { enumerable: true, configurable: true, writable: true, value: null }); } addComponent(component) { if (this.components.has(component.componentId)) { throw new Error(`Component ${component.constructor.name} already exists on entity ${this.name}`); } this.components.set(component.componentId, component); component.onStart?.(); return component; } getComponent(componentType) { return Array.from(this.components.values()).find((c) => c instanceof componentType); } removeComponent(componentType) { const component = this.getComponent(componentType); if (component) { component.onDestroy?.(); this.components.delete(component.componentId); } } addChild(child) { if (child.parent) child.parent.removeChild(child); this.children.add(child); child.parent = this; } removeChild(child) { if (this.children.delete(child)) { child.parent = null; } } setActive(active) { this.active = active; } update(deltaTime) { if (!this.active) return; for (const component of this.components.values()) { component.update?.(deltaTime, this); } for (const entity of this.children) { entity.update(deltaTime); } } destroy() { for (const component of this.components.values()) { component.onDestroy?.(); } for (const child of this.children) { child.destroy(); } if (this.parent) { this.parent.removeChild(this); } this.components.clear(); this.children.clear(); } } //# sourceMappingURL=Entity.js.map