计算FPS Javascript(我做错了什么吗?



这是我的计算FPS函数:

function calculateFPS() {
const now = performance.now();
if(fps.lastCalledTime !== null) {
fps.counter++;
const secondsPerFrame = (now - fps.lastCalledTime) / 1000;
fps.totalFPS += 1 / secondsPerFrame;
if(fps.counter === 20) {
fps.fps = Math.round(fps.totalFPS / fps.counter);
fps.totalFPS = 0;
fps.counter = 0;
}
}
fps.lastCalledTime = now;
}

这是我的 fps 全局对象:

let fps = {
lastCalledTime: null,
fps: 60,
counter: 0,
totalFPS: 0,
}

但是当我看到我的游戏变慢时(游戏正在割草(如果我翻译正确的话((,基本上 FPS 应该下降......相反,它会上升到400-500

我做错了什么吗?

提前谢谢你...

您可以这样计算两次函数调用之间的时间差

let then = performance.now();
let now;
let frame = 1000/60;
function animate() {
now = performance.now();
console.log(((now - then)/frame) * 60);
then = now;
}
setInterval(animate, frame);

最新更新