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.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  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, layerName) {
  25. this.layerName = layerName;
  26. this.level = level;
  27. this.bounds = new Rect();
  28. this.time = 0;
  29. this.traitOrder = [
  30. "collider",
  31. "platform",
  32. "wall",
  33. "keyboardController",
  34. "physics",
  35. ];
  36. this.t = {
  37. collider: null,
  38. platform: null,
  39. wall: null,
  40. keyboardController: null,
  41. physics: null,
  42. };
  43. this.traits = [];
  44. this.updateTraits = [];
  45. this.postUpdateTraits = [];
  46. }
  47. _init() {
  48. for (let traitName of this.traitOrder) {
  49. let t = this.t[traitName];
  50. if (t == null)
  51. continue;
  52. this.traits.push(t);
  53. if (t.update !== Trait.prototype.update)
  54. this.updateTraits.push(t);
  55. if (t.postUpdate !== Trait.prototype.postUpdate)
  56. this.postUpdateTraits.push(t);
  57. }
  58. for (let trait of this.traits) {
  59. trait._init();
  60. }
  61. this.init();
  62. }
  63. _update(dt) {
  64. for (let trait of this.updateTraits) {
  65. if (trait.enabled)
  66. trait.update(dt);
  67. }
  68. this.update(dt);
  69. this.time += dt;
  70. }
  71. _postUpdate(dt) {
  72. for (let trait of this.postUpdateTraits) {
  73. if (trait.enabled)
  74. trait.postUpdate(dt);
  75. }
  76. this.postUpdate(dt);
  77. }
  78. init() {}
  79. update(dt) {}
  80. postUpdate(dt) {}
  81. draw(ctx) {}
  82. has(name) {
  83. let t = this.t[name];
  84. return t != null && t.enabled;
  85. }
  86. addTrait(t) {
  87. if (this.t[t.name] === undefined)
  88. throw new Error("Invalid trait:", t);
  89. this.t[t.name] = t;
  90. }
  91. }