javascript PixiJS固定步长循环-断续/抖动

uqjltbpv  于 2022-12-28  发布在  Java
关注(0)|答案(1)|浏览(246)

我一直在面对一个奇怪的问题,我不知道如何解决它。
我正在尝试创建以下多人游戏结构:

  • 服务器以20-30 fps的速度运行
  • 客户端逻辑循环的FPS与服务器相同
  • 客户端呈现循环

我正在使用PixiJS作为UI,这里是我卡住的地方。( I've opened a thread here as well )
我这里有一个演示:https://playcode.io/1045459
好了,现在让我们来解释一下这个问题!

private update = () => {
    let elapsed = PIXI.Ticker.shared.elapsedMS
    if (elapsed > 1000) elapsed = this.frameDuration
    this.lag += elapsed

    //Update the frame if the lag counter is greater than or
    //equal to the frame duration
    while (this.lag >= this.frameDuration) {  

        //Update the logic
        console.log(`[Update] FPS ${Math.round(PIXI.Ticker.shared.FPS)}`)
        this.updateInputs(now())

        //Reduce the lag counter by the frame duration
        this.lag -= this.frameDuration
    }

    // Render elements in-between states
    const lagOffset = this.lag / this.frameDuration
    this.interpolateSpaceships(lagOffset)
}

在客户端循环中,我跟踪逻辑和渲染部分,将逻辑部分限制在20 fps。在浏览器的帧速率突然从120 fps下降到60 fps之前,所有的工作都是“cookie和云”。根据我的调查和帧速率下降时我整理的一个漂亮而混乱的电子表格,“播放器”移动2倍以上(如3.3而不是1.66)在纸上这是正常的,数学是正确的,但这造成了一个小反弹/抖动/口吃或任何命名这件事。
在我用playcode创建的演示中,它是不可见的。我的假设是代码太简单了,帧率从来没有下降过。
考虑到数学和算法是正确的(我还不确定),我把目光转向了其他可能会影响这一点的部分。我使用像素视口来跟随角色。会不会是下面的部分造成了这种反弹?
有没有人有写这样一个游戏循环的经验?
更新:Okkkk,令人兴奋的结果。我刚刚发现即使是有史以来最简单的游戏循环版本也会发生这种情况。只需每帧乘以x = x + speed * delta
同样的原因,FPS突然下降。

66bbxpm5

66bbxpm51#

好的,我找到了解决方法。我会把它贴在这里,因为没有太多的信息。解决方法是平滑多帧的突然下降。简单吧?😅

const ticker = new PIXI.Ticker();

// The number of frames to use for smoothing
const smoothingFrames = 10;

// The smoothed frame duration
let smoothedFrameDuration = 0;

ticker.add((deltaTime) => {
  // Add the current frame duration to the smoothing array
  smoothedFrameDuration = (smoothedFrameDuration * (smoothingFrames - 1) + deltaTime) / smoothingFrames;

  // Update the game logic here
  // Use the smoothed frame duration instead of the raw deltaTime value
});

ticker.start();

相关问题