GameHandler.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. const GameHandler = {
  2. nextId: 0,
  3. rootObjects: [],
  4. renderMode: null,
  5. bDrawDebugFPS: false,
  6. prevMillis: 0,
  7. delta: 0,
  8. setRenderMode: function(mode)
  9. {
  10. this.renderMode = mode;
  11. },
  12. drawDebugFPS(val)
  13. {
  14. this.bDrawDebugFPS = val;
  15. },
  16. init: function(fps = 60)
  17. {
  18. if (!this.renderMode) this.renderMode = RENDER_MODES.P2D;
  19. switch (this.renderMode)
  20. {
  21. case RENDER_MODES.P2D:
  22. createCanvas(windowWidth, windowHeight);
  23. break;
  24. case RENDER_MODES.WEBGL:
  25. createCanvas(windowWidth, windowHeight, WEBGL);
  26. break;
  27. }
  28. frameRate(fps);
  29. smooth();
  30. },
  31. instanceGameObject: function(obj)
  32. {
  33. obj.id = this.nextId;
  34. this.nextId++;
  35. },
  36. addRootObject: function(obj)
  37. {
  38. this.rootObjects.push(obj);
  39. },
  40. update: function()
  41. {
  42. this.delta = (millis() - this.prevMillis) / 1000;
  43. for (let i = 0; i < this.rootObjects.length; i++)
  44. this.rootObjects[i].update(this.delta);
  45. },
  46. draw: function()
  47. {
  48. if (this.renderMode == RENDER_MODES.WEBGL) translate(-windowWidth / 2, -windowHeight / 2);
  49. if (this.bDrawDebugFPS)
  50. {
  51. textSize(12);
  52. noStroke();
  53. fill(0);
  54. text("FPS: " + frameRate(), 10, 20);
  55. }
  56. for (let i = 0; i < this.rootObjects.length; i++)
  57. this.rootObjects[i].draw(this.delta);
  58. this.prevMillis = millis();
  59. }
  60. }