GameRenderer.js 2.61 KB
Newer Older
1
import GameConfig from "../config/GameConfiguration.js";
2
import Time from "../utils/Time.js";
3
import Enemy from "./objects/Enemy.js";
4

5
var canvas,
6
  context,
7
  fpsBuffer,
8 9
  currentFPS,
  lastDebugFrame = 0;
10

11 12
function draw(state, delta) {
  updateFPS(delta);
13
  context.clearRect(0, 0, canvas.width, canvas.height);
14
  drawEnemies(state.enemies);
15
  drawGazePoints(state.gazePoints);
16
  if (GameConfig.getShowDebugInfoOnScreen() === true) {
17 18 19 20
    drawDebugInfo();
  }
}

21
// TODO: Move fps callculation to manager since we need it there to use delta
22 23 24
function updateFPS(delta) {
  let fps = Time.ONE_SECOND_IN_MS / delta;
  fpsBuffer.push(fps);
25
  if (fpsBuffer.length === GameConfig.getFPSBufferLenght()) {
26 27 28 29
    currentFPS = parseInt(fpsBuffer.reduce((a, b) => a + b, 0) /
      fpsBuffer.length);
    fpsBuffer.shift();
  }
30 31
}

32 33 34
function drawEnemies(enemies) {
  for (let i = 0; i < enemies.length; i++) {
    Enemy.draw.call(enemies[i], context);
35
  }
36 37
}

38
function drawGazePoints(gazePoints) {
39
  context.fillStyle = GameConfig.getGazePointColor();
40 41
  for (let i = 0; i < gazePoints.length; i++) {
    drawSingleGazePoint(gazePoints[i]);
42 43 44
  }
}

45
function drawSingleGazePoint(gazePoint) {
46 47 48 49 50 51
  if(Date.now() - lastDebugFrame > 1000) {
    console.log(gazePoint);
    lastDebugFrame = Date.now();
    console.log((1 - gazePoint.relativeAge) * GameConfig.getGazePointRadius());
    console.log((1 - gazePoint.relativeAge));
  }
52
  let inversedAge = 1 - gazePoint.relativeAge,
53
    radius = inversedAge * GameConfig.getGazePointRadius();
54
  context.save();
55
  context.globalAlpha = inversedAge;
56
  context.globalAlpha = 1;
57
  context.beginPath();
58
  context.ellipse(gazePoint.screenX, gazePoint.screenY, radius, radius, Math.PI /
59 60 61 62
    4, 0, 2 * Math.PI);
  context.closePath();
  context.fill();
  context.restore();
63 64 65 66
}

function drawDebugInfo() {
  context.beginPath();
67 68
  context.font = GameConfig.getDebugInfoFont();
  context.fillStyle = GameConfig.getDebugInfoFonColor();
69 70
  context.fillText(`${GameConfig.getVersion()} | ${currentFPS}fps`, GameConfig.getDebugInfoPosition()
    .x, GameConfig.getDebugInfoPosition().y);
71 72 73 74 75
  context.closePath();
}

class GameRenderer {

76
  init(gameCanvas) {
77
    fpsBuffer = [];
78 79
    currentFPS = 0;
    canvas = gameCanvas;
80 81 82 83
    canvas.width = GameConfig.getScreenWidth();
    canvas.height = GameConfig.getScreenHeight();
    canvas.style.width = `${GameConfig.getScreenWidth()}px`;
    canvas.style.height = `${GameConfig.getScreenHeight()}px`;
84
    context = canvas.getContext("2d", { alpha: false });
85
    canvas.style.backgroundColor = GameConfig.getWorldBackgroundColor();
86 87
  }

88 89
  render(state, delta) {
    draw(state, delta);
90 91 92 93 94
  }

}

export default new GameRenderer();