我写了一个组件来显示当前的FPS。
它的最重要的部分是:如何在XNA中正确计算FPS?
public override void Update(GameTime gameTime)
{
elapseTime += (float)gameTime.ElapsedRealTime.TotalSeconds;
frameCounter++;
if (elapseTime > 1)
{
FPS = frameCounter;
frameCounter = 0;
elapseTime = 0;
}
base.Update(gameTime);
}
public override void Draw(GameTime gameTime)
{
spriteBatch.Begin();
spriteBatch.DrawString(font, "FPS " + ((int)FPS).ToString(), position, color, 0, origin, scale, SpriteEffects.None, 0);
spriteBatch.End();
base.Draw(gameTime);
}
在大多数情况下,它工作正常,但最近我有一个问题。
当我将下面的代码放入游戏的更新方法时,奇怪的事情开始发生。这段代码的
if (threadPath == null || threadPath.ThreadState != ThreadState.Running)
{
ThreadStart ts = new ThreadStart(current.PathFinder.FindPaths);
threadPath = new Thread(ts);
threadPath.Priority = ThreadPriority.Highest;
threadPath.Start();
}
主要思想是在不同的线程中运行寻路算法所有的时间。
奇怪的事情我的意思是,有时FPS剧烈下降,这是显而易见的,但显示FPS的变化比每秒一次更频繁。如果我理解这个代码,FPS不可能每秒更换一次。
有人能解释我发生了什么事吗?
编辑26.03.2010
我已经发布了Draw方法的代码。
编辑31.03.2010答案Venesectrix问题
1)给你一个固定或可变的时间步运行?
IsFixedTimeStep和SynchronizeWithVerticalRetrace设置为true。
2)发生这种情况时,您是否在移动XNA窗口?
否
3)XNA窗口是否有焦点?
是
4)它有多明显?(即更新速度如此之快以至于无法读取,或者只是几乎没有更新)?
我能够读取更新,FPS每秒更新〜3次。
5)所有这一切只发生在那里的线程代码?
是的
。 elapseTime = 0;} – Martin 2010-03-24 23:03:08
哦,并明显将framecount设置为零 – Martin 2010-03-24 23:08:45
@Martin:当然你是对的,它会提高精度,但它不会解决我的问题。不管怎么说,还是要谢谢你。 – 2010-03-24 23:09:22