我试图追踪所发生事情的所有可能性,但我正在学习Javascript,所以它必须是我不知道的东西。具体问题在于pongGame构造函数/函数;但是,我已经将我的整个代码包含在内,这是必要的。我认为,在我的gameLoop函数中,在pongGame构造函数中声明,变量pongGame.delta将等于10;因为,这就是我所宣称的。但是,它等于NaN。究竟是什么问题发生在这里?谢谢:))
var keys = [false, false, false, false];
var cavnas = document.getElementById("canvas");
var context = cavnas.getContext("2d");
(function() {
startUp();
})();
function startUp() {
resize();
window.addEventListener("resize", resize);
var game = new pongGame();
game.start();
}
function resize() {
document.getElementById("canvas").width = window.innerWidth;
document.getElementById("canvas").height = window.innerHeight;
}
function pongGame() {
this.delta = 10;
this.lastTime = 0;
this.ball = new ball();
this.start = function() {
this.gameLoop();
}
this.update = function() {
this.ball.update();
}
this.render = function() {
context.clearRect(0, 0, window.innerWidth, window.innerHeight);
this.ball.render();
}
var pongGame = this;
this.gameLoop = function(timestamp) {
console.log(pongGame.delta); // 10
pongGame.delta += timestamp - pongGame.lastTime;
while (pongGame.delta > (1000 / 60)) {
pongGame.update();
pongGame.delta -= (1000/60);
}
pongGame.render();
pongGame.lastTime = timestamp;
requestAnimationFrame(pongGame.gameLoop);
}
}
function paddle() {
}
function ball() {
this.x = 1;
this.y = 1;
this.xspeed = 1;
this.yspeed = 1;
this.size = 10;
this.update = function() {
if (this.x == 0 || this.x == window.innerWidth - this.size) {
this.xspeed = -this.xspeed;
}
if (this.y == 0 || this.y == window.innerHeight - this.size) {
this.yspeed = -this.yspeed;
}
this.x += this.xspeed;
this.y += this.yspeed;
}
this.render = function() {
context.beginPath();
context.arc(this.x, this.y, this.size, 0, Math.PI * 2);
context.fill();
}
}
答案 0 :(得分:2)
第一次调用pongGame.delta += timestamp - pongGame.lastTime;
时,您没有传递时间戳,因此此表达式delta
在第一次运行时将this.start = function() {
this.gameLoop(0);
}
设置为NAN,然后是所有后续运行(具有时间戳) )因为它已经是NAN
也许第一次用0调用它
{{1}}