您的位置:首页 > 编程语言

【XNA 4】XNA游戏中用于计算帧数FPS的游戏组件(GameComponent)的源代码!!

2012-07-03 17:57 387 查看
/// <summary>
/// This is a game component that implements IUpdateable.
/// </summary>
public class FrameRateCounter : Microsoft.Xna.Framework.DrawableGameComponent
{
ContentManager content;
SpriteBatch spriteBatch;
SpriteFont spriteFont;

int frameRate = 0;
int frameCounter = 0;
TimeSpan elapsedTime = TimeSpan.Zero;

public FrameRateCounter(Game game, SpriteBatch spriteBatch)
: base(game)
{
content = new ContentManager(game.Services);
LoadGraphicsContent(true);
this.spriteBatch = spriteBatch;
}

protected void LoadGraphicsContent(bool loadAllContent)
{
if (loadAllContent)
{
spriteFont = content.Load<SpriteFont>(@"Content\HudFont");   // 指定SpriteFont
}
}

public override void Update(GameTime gameTime)
{
elapsedTime += gameTime.ElapsedGameTime;

if (elapsedTime > TimeSpan.FromSeconds(1))
{
elapsedTime -= TimeSpan.FromSeconds(1);
frameRate = frameCounter;
frameCounter = 0;
}
}

public override void Draw(GameTime gameTime)
{
frameCounter++;

string fps = string.Format("FPS: {0}", frameRate);

spriteBatch.Begin();

spriteBatch.DrawString(spriteFont, fps, new Vector2(20, 20), Color.White);    // 坐标根据需要自行修改

spriteBatch.End();
}
}


需要用的时候只要在LoadContent的spriteBatch初始化之后用

Component.Add(new FrameRateCounter(this, spriteBatch));


即可。

另外注意,需要自行修改一下你用来显示FPS的SpriteFont文件,和要显示FPS的坐标。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: