123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112 |
- 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, layerName) {
- this.layerName = layerName;
- this.level = level;
- this.bounds = new Rect();
- this.time = 0;
-
- this.traitOrder = [
- "collider",
- "platform",
- "wall",
- "keyboardController",
- "physics",
- ];
- this.t = {
- collider: null,
- platform: null,
- wall: null,
- keyboardController: 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.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;
- }
- }
|