XNA 4.0 C# 限制 FPS

XNA 4.0 C# limit FPS

我正在尝试限制我的 Monogame XNA 项目的 'frames per second',但我的 limitFrames 函数不准确。

例如,我的项目 运行 帧率为 60 fps,没有限制器。但是当我使用限制器并将 frameRateLimiter 变量设置为每秒 30 帧时,项目的最大 fps 约为 27.

有人能想出解决办法吗?

帧限制器代码

private float frameRateLimiter = 30f;
// ...

protected override void Draw(GameTime gameTime)
{
    float startDrawTime = gameTime.TotalGameTime.Milliseconds;
    limitFrames(startDrawTime, gameTime);
    base.Draw(gameTime);
}

private void limitFrames(float startDrawTime, GameTime gameTime)
{
    float durationTime = startDrawTime - gameTime.TotalGameTime.Milliseconds;
    // FRAME LIMITER
    if (frameRateLimiter != 0)
    {
        if (durationTime < (1000f / frameRateLimiter))
        {
            // *THE INACCERACY IS MIGHT COMING FROM THIS LINE*
            System.Threading.Thread.Sleep((int)((1000f / frameRateLimiter) - durationTime));
        }
     }
}

淋浴每秒帧数

public class FramesPerSecond
{
    // The FPS
    public float FPS;

    // Variables that help for the calculation of the FPS
    private int currentFrame;
    private float currentTime;
    private float prevTime;
    private float timeDiffrence;
    private float FrameTimeAverage;
    private float[] frames_sample;
    const int NUM_SAMPLES = 20;

    public FramesPerSecond()
    {
        this.FPS = 0;
        this.frames_sample = new float[NUM_SAMPLES];
        this.prevTime = 0;
    }

    public void Update(GameTime gameTime)
    {
        this.currentTime = (float)gameTime.TotalGameTime.TotalMilliseconds;
        this.timeDiffrence = currentTime - prevTime;
        this.frames_sample[currentFrame % NUM_SAMPLES] = timeDiffrence;
        int count;
        if (this.currentFrame < NUM_SAMPLES)
        {
            count = currentFrame;
        }
        else
        {
            count = NUM_SAMPLES;
        }
        if (this.currentFrame % NUM_SAMPLES == 0)
        {
            this.FrameTimeAverage = 0;
            for (int i = 0; i < count; i++)
            {
                this.FrameTimeAverage += this.frames_sample[i];
            }
            if (count != 0)
            {
                this.FrameTimeAverage /= count;
            }
            if (this.FrameTimeAverage > 0)
            {
                this.FPS = (1000f / this.FrameTimeAverage);
            }
            else
            {
                this.FPS = 0;
            }
        }
        this.currentFrame++;
        this.prevTime = this.currentTime;
}

你不需要重新发明轮子。

MonoGameXNA 已经有内置变量来为您处理这个问题。

要将帧速率限制为最大 30fps,请在 Initialize() 方法中将 IsFixedTimeStepTargetElapsedTime 设置为以下内容:

IsFixedTimeStep = true;  //Force the game to update at fixed time intervals
TargetElapsedTime = TimeSpan.FromSeconds(1 / 30.0f);  //Set the time interval to 1/30th of a second

您的游戏的 FPS 可以使用以下方法进行评估:

//"gameTime" is of type GameTime
float fps = 1f / gameTime.ElapsedGameTime.TotalSeconds;