簡體   English   中英

XNA 4.0 C#極限FPS

[英]XNA 4.0 C# limit FPS

我試圖限制Monogame XNA項目的“每秒幀數”,但我的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;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM