diff --git a/src/game.js b/src/game.js index 66bd791..203ef1c 100644 --- a/src/game.js +++ b/src/game.js @@ -3,6 +3,8 @@ import Input from "./input.js" import Event from "./event.js" import Message from "./message.js" +import { average } from "./util.js" + export default class Game { constructor(canvas) { this.canvas = canvas @@ -21,6 +23,8 @@ export default class Game { } this.message = null + + this.fpsBuffer = [60, 60, 60, 60, 60, 60, 60, 60, 60, 60] } triggerEvent(eventName, object) { @@ -45,6 +49,9 @@ export default class Game { loop(timestamp) { this.dt = timestamp - this.timestamp + const fps = 1000 / this.dt + this.fpsBuffer.pop() + this.fpsBuffer.unshift(fps) this.timestamp= timestamp this.tick(this.dt) this.draw() @@ -72,11 +79,12 @@ export default class Game { drawFps(ctx) { ctx.fillStyle = "white" - ctx.fillRect(0, 0, 25, 20) + ctx.fillRect(ctx.canvas.width, 0, -25, 20) ctx.strokeStyle = "black" ctx.textBaseline = "top" + ctx.textAlign = "right" ctx.font = "bold 20px serif" - ctx.fillText(Math.round(1000 / this.dt), 0, 0) - ctx.strokeText(Math.round(1000 / this.dt), 0, 0) + ctx.fillText(Math.round(average(this.fpsBuffer)), ctx.canvas.width, 0) + ctx.strokeText(Math.round(average(this.fpsBuffer)), ctx.canvas.width, 0) } } diff --git a/src/util.js b/src/util.js index 7b2e40d..49c7515 100644 --- a/src/util.js +++ b/src/util.js @@ -14,8 +14,17 @@ const doLengthsOverlap = (l1, l2) => { return !((l1.x + l1.width < l2.x) || (l2.x + l2.width) < l1.x) } +function sum(array) { + return array.reduce((a, b) => a + b, 0) +} + +function average(array) { + return sum(array) / array.length +} + export { SQRT_OF_TWO, isZeroVector, - doRectanglesOverlap + doRectanglesOverlap, + sum, average }