You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Entity.js 1.5KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. import Rect from "./Rect.js";
  2. export class Trait {
  3. constructor(entity, name, deps = []) {
  4. this.name = name;
  5. this.entity = entity;
  6. this.enabled = true;
  7. this.deps = deps;
  8. }
  9. _init() {
  10. let missing = [];
  11. this.deps.forEach(d => {
  12. if (!this.entity.has(d))
  13. missing.push(d);
  14. });
  15. if (missing.length > 0)
  16. throw new Error("Missing dependency traits: "+missing.join(", "));
  17. this.init();
  18. }
  19. init() {}
  20. update(dt) {}
  21. postUpdate(dt) {}
  22. }
  23. export default class Entity {
  24. constructor(level) {
  25. this.level = level;
  26. this.bounds = new Rect();
  27. this.t = {
  28. physics: null,
  29. keyboardController: null,
  30. collider: null,
  31. platform: null,
  32. };
  33. this.traits = [];
  34. this.updateTraits = [];
  35. this.postUpdateTraits = [];
  36. }
  37. _init() {
  38. for (let trait of this.traits) {
  39. trait._init();
  40. }
  41. this.init();
  42. }
  43. _update(dt) {
  44. for (let trait of this.updateTraits) {
  45. if (trait.enabled)
  46. trait.update(dt);
  47. }
  48. this.update(dt);
  49. }
  50. _postUpdate(dt) {
  51. for (let trait of this.postUpdateTraits) {
  52. if (trait.enabled)
  53. trait.postUpdate(dt);
  54. }
  55. this.postUpdate(dt);
  56. }
  57. init() {}
  58. update(dt) {}
  59. postUpdate(dt) {}
  60. draw(ctx) {}
  61. has(name) {
  62. let t = this.t[name];
  63. return t != null && t.enabled;
  64. }
  65. addTrait(t) {
  66. if (this.t[t.name] === undefined)
  67. throw new Error("Invalid trait:", t);
  68. this.t[t.name] = t;
  69. this.traits.push(t);
  70. if (t.update !== Trait.prototype.update)
  71. this.updateTraits.push(t);
  72. if (t.postUpdate !== Trait.prototype.postUpdate)
  73. this.postUpdateTraits.push(t);
  74. }
  75. }