GameManager.js 2.05 KB
Newer Older
Alexander Bazo committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92
import Logger from "../utils/Logger.js";

const BACKGROUND_COLOR = "rgba(30,30,30,0.5)",
  DEFAULT_GAZE_POINT_RADIUS = 10,
  DEFAULT_GAZE_POINT_COLOR = "#ff007b",
  MAX_GAZE_POINT_AGE = 500;

var lastUpdate,
  lastDelta;

class GameManger {

  constructor() {
    this.gazePoints = new Map();
  }

  setCanvas(canvas) {
    this.canvas = canvas;
    this.context = this.canvas.getContext("2d");
    this.canvas.style.backgroundColor = BACKGROUND_COLOR;
  }

  setFrameRate(fps) {
    this.fps = fps;
  }

  setSize(width, height) {
    this.canvas.width = width;
    this.canvas.height = height;
    this.canvas.style.width = `${width}px`;
    this.canvas.style.height = `${height}px`;
  }

  start() {
    let targetFrameTime = 1000 / this.fps;
    this.setUpdateTime();
    this.loop = setInterval(this.onTick.bind(this), targetFrameTime);
  }

  setUpdateTime() {
    lastUpdate = Date.now();
  }

  setDelta() {
    lastDelta = Date.now() - lastUpdate;
  }

  addGazePoint(point) {
    this.gazePoints.set(point.id, point);
  }

  removeGazePoint(point) {
    this.gazePoints.delete(point.id);
  }

  onTick() {
    this.setDelta();
    this.updateGazePoints();
    this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
    this.drawGazePoints();
    this.setUpdateTime();
  }

  updateGazePoints() {
    let now = Date.now();
    for (let item of this.gazePoints) {
      let point = item[1];
      if (now - point.createdAt > MAX_GAZE_POINT_AGE) {
        this.removeGazePoint(point);
      }
    }
  }

  drawGazePoints() {
    let now = Date.now();
    this.context.fillStyle = DEFAULT_GAZE_POINT_COLOR;
    for (let item of this.gazePoints) {
      this.context.save();
      this.context.globalAlpha = 1 - (now - item[1].createdAt) / MAX_GAZE_POINT_AGE;
      this.context.beginPath();
      this.context.ellipse(item[1].targetX, item[1].targetY,
        DEFAULT_GAZE_POINT_RADIUS, DEFAULT_GAZE_POINT_RADIUS, Math.PI / 4,
        0, 2 * Math.PI);
      this.context.fill();
      this.context.closePath();
      this.context.restore();
    }
  }

}

export default GameManger;