123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152 |
- const GameHandler = {
- nextId: 0,
- rootObjects: [],
- renderMode: null,
- bDrawDebugFPS: false,
- debugFpsLabel: null,
- prevMillis: 0,
- delta: 0,
- db: null,
- dbWidth: 1920,
- dbHeight: 1080,
- setRenderMode: function(mode)
- {
- this.renderMode = mode;
- },
- setDoubleBufferSize: function(w, h)
- {
- this.dbWidth = w;
- this.dbHeight = h;
- },
- drawDebugFPS(val)
- {
- this.bDrawDebugFPS = val;
- },
- init: function(fps = 60)
- {
- if (!this.renderMode) this.renderMode = RENDER_MODES.P2D;
- switch (this.renderMode)
- {
- case RENDER_MODES.P2D:
- createCanvas(windowWidth, windowHeight);
- this.db = createGraphics(this.dbWidth, this.dbHeight);
- break;
- case RENDER_MODES.WEBGL:
- createCanvas(windowWidth, windowHeight, WEBGL);
- this.db = createGraphics(this.dbWidth, this.dbHeight, WEBGL);
- this.db.smooth();
- break;
- }
- frameRate(fps);
- smooth();
- if (this.renderMode == RENDER_MODES.WEBGL)
- {
- translate(-windowWidth / 2, -windowHeight / 2);
- db.translate(-this.dbWidth / 2, -this.dbHeight / 2);
- }
- if (this.bDrawDebugFPS)
- {
- this.debugFpsLabel = new Label("debugFps", `FPS: ${frameRate()}`);
- this.addRootObject(this.debugFpsLabel);
- }
- },
- instanceGameObject: function(obj)
- {
- obj.id = this.nextId;
- this.nextId++;
- },
- addRootObject: function(obj)
- {
- this.rootObjects.push(obj);
- obj.setup();
- },
- upframecount: 0,
- upframenum: 20,
- update: function()
- {
- if (this.bDrawDebugFPS)
- {
- if (frameCount % this.upframenum == 0)
- {
- this.debugFpsLabel.setText(`FPS: ${
- Math.round(this.upframecount * 1000) / 1000
- }`);
- this.upframecount = 0;
- }
- else
- this.upframecount = max(this.upframecount, frameRate());
- }
- this.delta = (millis() - this.prevMillis) / 1000;
- for (let i = 0; i < this.rootObjects.length; i++)
- this.rootObjects[i].update(this.delta);
- },
- draw: function()
- {
- this.db.clear();
- for (let i = 0; i < this.rootObjects.length; i++)
- this.rootObjects[i].draw(this.delta, this.db);
- this.db.push();
- this.db.strokeWeight(5);
- this.db.noFill();
- this.db.rect(0, 0, this.dbWidth, this.dbHeight);
- this.db.pop();
- imageMode(CENTER);
- if (windowWidth / windowHeight < this.dbWidth / this.dbHeight)
- {
- this.db.screenWidth = windowWidth;
- this.db.screenHeight = windowWidth * (this.dbHeight / this.dbWidth);
- }
- else
- {
- this.db.screenHeight = windowHeight;
- this.db.screenWidth = windowHeight * (this.dbWidth / this.dbHeight);
- }
- image(this.db, windowWidth / 2, windowHeight / 2, this.db.screenWidth, this.db.screenHeight);
- this.prevMillis = millis();
- }
- }
- function windowResized()
- {
- resizeCanvas(windowWidth, windowHeight);
- }
|