GameHandler.js 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. /************************************************************************
  2. * GameHandler.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. const GameHandler = {
  22. nextId: 0,
  23. rootObjects: [],
  24. renderMode: null,
  25. bDrawDebugFPS: false,
  26. debugFpsLabel: null,
  27. prevMillis: 0,
  28. delta: 0,
  29. setRenderMode: function(mode)
  30. {
  31. this.renderMode = mode;
  32. },
  33. drawDebugFPS(val)
  34. {
  35. this.bDrawDebugFPS = val;
  36. },
  37. init: function(fps = 60)
  38. {
  39. if (!this.renderMode) this.renderMode = RENDER_MODES.P2D;
  40. switch (this.renderMode)
  41. {
  42. case RENDER_MODES.P2D:
  43. createCanvas(windowWidth, windowHeight);
  44. break;
  45. case RENDER_MODES.WEBGL:
  46. createCanvas(windowWidth, windowHeight, WEBGL);
  47. break;
  48. }
  49. frameRate(fps);
  50. smooth();
  51. if (this.bDrawDebugFPS)
  52. this.debugFpsLabel = new Label(`FPS: ${frameRate()}`)
  53. },
  54. instanceGameObject: function(obj)
  55. {
  56. obj.id = this.nextId;
  57. this.nextId++;
  58. },
  59. addRootObject: function(obj)
  60. {
  61. this.rootObjects.push(obj);
  62. obj.setup();
  63. },
  64. update: function()
  65. {
  66. if (this.bDrawDebugFPS) this.debugFpsLabel.setText(`FPS: ${frameRate()}`)
  67. this.delta = (millis() - this.prevMillis) / 1000;
  68. for (let i = 0; i < this.rootObjects.length; i++)
  69. this.rootObjects[i].update(this.delta);
  70. },
  71. draw: function()
  72. {
  73. if (this.renderMode == RENDER_MODES.WEBGL)
  74. translate(-windowWidth / 2, -windowHeight / 2);
  75. for (let i = 0; i < this.rootObjects.length; i++)
  76. this.rootObjects[i].draw(this.delta);
  77. this.prevMillis = millis();
  78. }
  79. }
  80. function windowResized()
  81. {
  82. resizeCanvas(windowWidth, windowHeight);
  83. }