【问题标题】:Calculating FPS Javascript ( Do I make something wrong? )计算 FPS Javascript(我做错了吗?)
【发布时间】:2017-07-24 20:12:18
【问题描述】:

这是我的 calculateFPS 函数:

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

我做错了吗?

提前谢谢你...

【问题讨论】:

    标签: javascript frame-rate


    【解决方案1】:

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

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

    【讨论】:

    • 我已经阅读了使用 Date.now() 在那种功能中不好的帖子。另外我不需要计算两个函数之间的时间差。我需要 FPS,请告诉我为什么当游戏变慢时我的 FPS 会变大?不应该倒过来吗?甚至为什么有时我的 FPS 会在 400 - 500 FPS 之间(WTF?? 400 - 500 FPS 在今天的机器上甚至是不可能的)......我对你的答案不满意,所以我没有将其标记为正确答案
    • 它也适用于 performance.now。你想的太复杂了,你不需要一个每帧加 1 的 fps 计数器。在此示例中,以毫秒为单位的差异除以理想情况下一帧应占用的毫秒数,即 1000/60。您可以在此处看到一个有效的 jsfiddle:jsfiddle.net/w4waap2p/3 控制台将显示 fps 计数在 59 和 61 之间波动,具体取决于您的环境。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-15
    • 2022-08-16
    • 2012-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-15
    相关资源
    最近更新 更多