【发布时间】:2021-11-19 19:43:48
【问题描述】:
const canvas = document.querySelector('#canvas')
const context = canvas.getContext('2d')
let rectX = 0 ;
let rectY = 0;
let secondsPassed = 0;
let timeStamp = 0
let oldTimeStamp = 0;
let movingSpeed = 50;
gameLoop()
function draw() {
context.fillStyle = 'red';
context.fillRect(rectX, rectY, 150, 100);
}
function gameLoop(timeStamp) {
// Calculate how much time has passed
secondsPassed = (timeStamp - oldTimeStamp) / 1000;
oldTimeStamp = timeStamp;
update(secondsPassed);
draw();
window.requestAnimationFrame(gameLoop);
}
function update(secondsPassed) {
rectX += (movingSpeed * secondsPassed);
rectY += (movingSpeed * secondsPassed);
}
rectX 和 rectY 最初有一个数字值,movingSpeed 也有一个数字值, secondsPassed 也是如此。我的问题是为什么函数“更新”将 NaN 赋予变量 rectX 和 rectY ?控制台中没有显示错误。我尝试记录并使用 typeof 来检查每个变量是否都有一个类型编号的值,我注意到 rectX 曾经被认为是一个字符串,我试图解析 rectX 但它仍然给了我 NaN。通常,我们使用 timeStamp 返回一个可以帮助我们计算 fps 的值。在这种情况下,我使用 timeStamp 来查看在运行函数 gameLoop 之前已经过去了多少秒。我这样做是因为决定游戏速度的不再是帧速率(和硬件),而是时间。
更新:已解决,感谢 @epascarello、@James 和 @Kaiido。有更新的代码给你们:
const canvas = document.querySelector('#canvas')
const context = canvas.getContext('2d')
let rectX = 0;
let rectY = 0;
let secondsPassed = 0;
let oldTimeStamp = 0;
let timeStamp = 0
let movingSpeed = 50;
let timePassed = 0
function draw() {
context.fillStyle = 'red';
context.fillRect(rectX, rectY, 150, 100);
}
function gameLoop(timeStamp) {
// Calculate how much time has passed
secondsPassed = (timeStamp - oldTimeStamp) / 1000;
oldTimeStamp = timeStamp;
// Pass the time to the update
update(secondsPassed);
draw();
window.requestAnimationFrame(function(timeStamp){gameLoop(timeStamp)});
}
function update(secondsPassed) {
// Use time to calculate new position
rectX += (movingSpeed * secondsPassed);
rectY += (movingSpeed * secondsPassed);
}
window.requestAnimationFrame(function(timeStamp){gameLoop(timeStamp)});
【问题讨论】:
-
添加console.log()看看什么是NaN
-
rectX和rextY最初是undefined。 -
因为你从不传入
timeStamp看看gameLoop()function gameLoop(timeStamp) {带有变量的简单console.log() 会让你看到这一点。 -
timeStamp应该是什么?当前未定义,这将使 oldTimestamp 未定义,这将使 secondsPassed NaN,这将破坏 rectX 和 rectY。 -
也从
requestAnimationFrame(gameLoop)调用您的第一个gameLoop,或将timestamp初始化为document.timeline.currentTime
标签: javascript animation canvas