Javascript画布游戏三角洲时间

时间:2018-03-26 16:35:56

标签: javascript canvas requestanimationframe

我正在开发一个简单的基于javascript画布的游戏,一切顺利,除了试图获得增量时间来计算。我已经按照我能找到的每个教程进行了操作,并且我仍然为delta时间变量得到0,这导致没有动画...请有人向我解释我在这里做错了什么

export default class {
  constructor(options) {

  // Window Variables
  this.canvas;
  this.ctx;
  this.width;
  this.height;
  this.running = false;

  // Time Variables
  this.fps = 30;
  this.timePerTick = 1000/this.fps;
  this.delta = 0;
  this.now;
this.lastTime = Date.now();
this.timer = 0;
this.ticks = 0;

if(options != null) {

  if(options.width != null) 
    this.width = options.width;

  if(options.height != null)
    this.height = options.height;

  if(options.id != null) {
    document.body.innerHTML = "<canvas id='"+options.id+"' width='"+this.width+"' height='"+this.height+"'><canvas>";
  }
}

this.canvas = document.getElementById(options.id);
this.canvas.width = this.width;
this.canvas.height = this.height;

  this.ctx = this.canvas.getContext('2d');
}

init(callback) {

  callback();
  this.running = true;
}

update(callback) {

  if(this.running) {
    this.now = Date.now();
    this.delta = this.now - this.lastTime;
    this.timer += this.delta;
    this.lastTime = this.now;
  }

  if(this.timer >= this.timePerTick) {
    this.dt = this.timer/1000;
    callback();
    this.timer = 0;
  }

  requestAnimationFrame(() => {this.update});
}
}

1 个答案:

答案 0 :(得分:0)

从我在这里可以看出,你并没有在每一帧调用update。如果你需要做更多的事情而不是调用update,那么传递箭头函数就像你一样。但是当前的箭头函数不会返回requestAnimationFrame所需的回调。

只需将update传递给requestAnimationFrame