GameHandler.js 1.7 KB

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