I am trying to add secondsPassed to timePassed but when doing so I get NaN.
I can’t find anything wrong so why is timePassed = NaN when adding secondsPassed to it?
var secondsPassed = 0;
var oldTimeStamp = 0;
let fps;
var posX = 0, posY = 0;
var timePassed = 0.0;
setTimeout(gameLoop, 100);
function gameLoop(timeStamp){
//seconds since last frame
secondsPassed = (timeStamp - oldTimeStamp) / 1000;
oldTimeStamp = timeStamp;
// Move forward in time with a maximum amount
secondsPassed = Math.min(secondsPassed, 0.1);
//calculate fps
fps = Math.round(1 / secondsPassed);
//run game functions
update(secondsPassed);
//loop again
window.requestAnimationFrame(gameLoop);
}
function update(secondsPassed){
console.log(secondsPassed);
timePassed += secondsPassed;
console.log(timePassed);
posX = 200 * timePassed;
posY = 400;
}Advertisement
Answer
You don’t seem to pass timeStamp argument to gameLoop() function. Passing it fixes the issue. Also make sure, your oldTimeStamp is initialized.
+new Date() is a way to create a timestamp from Date object.
let secondsPassed;
let oldTimeStamp = +new Date() - (60*5);
let fps;
let frame;
let posX = 0, posY = 0;
let timePassed = 0;
setTimeout(gameLoop(+new Date()), 1000);
function update(secondsPassed){
console.log("sec: " + secondsPassed);
timePassed += secondsPassed;
console.log("time: " + timePassed);
posX = 200 * timePassed;
posY = 400;
}
function gameLoop(timeStamp){
//seconds since last frame
secondsPassed = (timeStamp - oldTimeStamp) / 1000;
oldTimeStamp = timeStamp;
// Move forward in time with a maximum amount
secondsPassed = Math.min(secondsPassed, 0.1);
//calculate fps
fps = Math.round(1 / secondsPassed);
frame++;
update(secondsPassed);
//draw();
//run game functions
//loop again
window.requestAnimationFrame(gameLoop);
}