Steve Knabe Steve Knabe - 5 months ago 7
Javascript Question

Javascript constructor variable NAN inside function

I've tried to trace through all the possibilities of what's happening, but I'm learning Javascript so it has to be something I just don't know. The specific issue lies within the pongGame constructor/function; however, I have included my entire code just encase it is necessary. I would assume that, inside my gameLoop function which declared within the pongGame constructor, the variable pongGame.delta would be equal to 10; For, that is what I declared it to be. However, it is equal to NaN. What exactly is the issue that is happening here? Thanks :)

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();
}
}

Answer

The first time you call gameLoop you do not pass a timestamp so this expression pongGame.delta += timestamp - pongGame.lastTime; sets delta to NAN the first time its ran and then all subsequent runs (which have a timestamp) since its already NAN.
Maybe call it with 0 the first time

this.start = function() {
    this.gameLoop(0);
}
Comments