GameHandler.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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. obj.setup();
  43. },
  44. update: function()
  45. {
  46. if (this.bDrawDebugFPS) this.debugFpsLabel.setText(`FPS: ${frameRate()}`)
  47. this.delta = (millis() - this.prevMillis) / 1000;
  48. for (let i = 0; i < this.rootObjects.length; i++)
  49. this.rootObjects[i].update(this.delta);
  50. },
  51. draw: function()
  52. {
  53. if (this.renderMode == RENDER_MODES.WEBGL)
  54. translate(-windowWidth / 2, -windowHeight / 2);
  55. for (let i = 0; i < this.rootObjects.length; i++)
  56. this.rootObjects[i].draw(this.delta);
  57. this.prevMillis = millis();
  58. }
  59. }
  60. function windowResized()
  61. {
  62. resizeCanvas(windowWidth, windowHeight);
  63. }