简体   繁体   中英

Adding a number to number results in NaN in my program. WHY?

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

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

Math.min returns NaN if any of its parameters is converted into numbers. So, check your code before that, what value is passed due to which it gives NaN. Also, read this Math.min May be the one of the timestamp is a object type.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM