我试图限制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;
}
答案 0 :(得分:3)
您不需要重新发明轮子。
MonoGame 和 XNA 已经具有内置变量来为您处理。
要将帧率限制为最大30fps,请在IsFixedTimeStep
方法中将TargetElapsedTime
和Initialize()
设置为以下值:
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;