1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798 |
- import Rect from "./Rect.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) {
- this.level = level;
- this.bounds = new Rect();
- this.time = 0;
-
- this.t = {
- physics: null,
- keyboardController: null,
- collider: null,
- platform: null,
- wall: null,
- };
-
- this.traits = [];
- this.updateTraits = [];
- this.postUpdateTraits = [];
- }
-
- _init() {
- 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.update(dt);
- this.time += dt;
- }
-
- _postUpdate(dt) {
- for (let trait of this.postUpdateTraits) {
- if (trait.enabled)
- trait.postUpdate(dt);
- }
-
- this.postUpdate(dt);
- }
-
- init() {}
- update(dt) {}
- postUpdate(dt) {}
-
- 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;
- this.traits.push(t);
-
- if (t.update !== Trait.prototype.update)
- this.updateTraits.push(t);
- if (t.postUpdate !== Trait.prototype.postUpdate)
- this.postUpdateTraits.push(t);
- }
- }
|