import Rect from "./Rect.js"; import Vec2 from "./Vec2.js"; export class Trait { constructor(entity, name, deps = []) { this.name = name; this.entity = entity; this.enabled = true; this.deps = deps; } _init() { let missing = []; this.deps.forEach(d => { if (!this.entity.has(d)) missing.push(d); }); if (missing.length > 0) throw new Error("Missing dependency traits: "+missing.join(", ")); this.init(); } init() {} update(dt) {} postUpdate(dt) {} } export default class Entity { constructor(level, layerName) { this.layerName = layerName; this.level = level; this.pos = new Vec2(); this.bounds = new Rect(this.pos); this.time = 0; this.traitOrder = [ "collider", "platform", "wall", "keyboardController", "behavior", "physics", ]; this.t = { collider: null, platform: null, wall: null, keyboardController: null, behavior: null, physics: null, }; this.traits = []; this.updateTraits = []; this.postUpdateTraits = []; } _init() { for (let traitName of this.traitOrder) { let t = this.t[traitName]; if (t == null) continue; this.traits.push(t); if (t.update !== Trait.prototype.update) this.updateTraits.push(t); if (t.postUpdate !== Trait.prototype.postUpdate) this.postUpdateTraits.push(t); } for (let trait of this.traits) { trait._init(); } this.init(); } _update(dt) { for (let trait of this.updateTraits) { if (trait.enabled) trait.update(dt); } this.time += dt; } _postUpdate(dt) { for (let trait of this.postUpdateTraits) { if (trait.enabled) trait.postUpdate(dt); } } init() {} draw(ctx) {} has(name) { let t = this.t[name]; return t != null && t.enabled; } addTrait(t) { if (this.t[t.name] === undefined) throw new Error("Invalid trait:", t); this.t[t.name] = t; } }