GameObject.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. /************************************************************************
  2. * GameObject.js
  3. ************************************************************************
  4. * Copyright (c) 2021 Pedro Tonini Rosenberg Schneider.
  5. *
  6. * This file is part of Pandora.
  7. *
  8. * Pandora is free software: you can redistribute it and/or modify
  9. * it under the terms of the GNU General Public License as published by
  10. * the Free Software Foundation, either version 3 of the License, or
  11. * (at your option) any later version.
  12. *
  13. * Pandora is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. * GNU General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU General Public License
  19. * along with Pandora. If not, see <https://www.gnu.org/licenses/>.
  20. *************************************************************************/
  21. class GameObject
  22. {
  23. constructor(name)
  24. {
  25. this.id = 0;
  26. this.name = name;
  27. this.children = [];
  28. this.parented = false;
  29. this.parent = null;
  30. this.isOnTree = false;
  31. GameHandler.instanceGameObject(this);
  32. }
  33. // Getters
  34. getChildren()
  35. {
  36. return this.children;
  37. }
  38. getChildByIndex(idx)
  39. {
  40. if (idx >= 0 && idx < this.children.length)
  41. return this.children[idx];
  42. return null;
  43. }
  44. getChildByName(name)
  45. {
  46. for (let i = 0; i < this.children.length; i++)
  47. if (this.children[i].name == name) return this.children[i];
  48. return null;
  49. }
  50. getParent()
  51. {
  52. if (!this.parented) return null;
  53. return this.parent;
  54. }
  55. // Methods
  56. addChild(child)
  57. {
  58. child.parent = this;
  59. child.parented = true;
  60. this.children.push(child);
  61. if (this.isOnTree) child.setup();
  62. }
  63. setup()
  64. {
  65. this.isOnTree = true;
  66. this._setup();
  67. for (let i = 0; i < this.children.length; i++)
  68. {
  69. this.children[i].setup();
  70. }
  71. }
  72. update(delta)
  73. {
  74. this._update(delta);
  75. for (let i = 0; i < this.children.length; i++)
  76. this.children[i].update(delta);
  77. }
  78. draw(delta)
  79. {
  80. this._draw(delta);
  81. for (let i = 0; i < this.children.length; i++)
  82. this.children[i].draw(delta);
  83. }
  84. // Callbacks
  85. _setup()
  86. {
  87. }
  88. _update(delta)
  89. {
  90. }
  91. _draw(delta)
  92. {
  93. }
  94. }