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

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