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

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