1

I have this code sample i need to find how to show/display the frames per second on the screen. Tried to use the class but its not working good im not sure how to use it.

protected override void Initialize()
{
    base.Initialize();

    fpsm = new FpsMonitor();
    fpsm.Update();
    fpsm.Draw(spriteBatch, fonts, new Vector2(5,5), Color.Red);

}

protected override void Update(GameTime gameTime)
{
    // Allows the game to exit
    if (GamePad.GetState(PlayerIndex.One).Buttons.Back ==
        ButtonState.Pressed)
        this.Exit();

    modelRotation += (float)gameTime.ElapsedGameTime.TotalMilliseconds *
        MathHelper.ToRadians(0.1f);

    base.Update(gameTime);
}

protected override void Draw(GameTime gameTime)
{
    graphics.GraphicsDevice.Clear(Color.CornflowerBlue);

    // Copy any parent transforms.
    Matrix[] transforms = new Matrix[myModel.Bones.Count];
    myModel.CopyAbsoluteBoneTransformsTo(transforms);

    // Draw the model. A model can have multiple meshes, so loop.
    foreach (ModelMesh mesh in myModel.Meshes)
    {
        // This is where the mesh orientation is set, as well 
        // as our camera and projection.
        foreach (BasicEffect effect in mesh.Effects)
        {
            effect.EnableDefaultLighting();
            effect.World = transforms[mesh.ParentBone.Index] *
                Matrix.CreateRotationY(modelRotation)
                * Matrix.CreateTranslation(modelPosition);
            effect.View = Matrix.CreateLookAt(cameraPosition,
                Vector3.Zero, Vector3.Up);
            effect.Projection = Matrix.CreatePerspectiveFieldOfView(
                MathHelper.ToRadians(45.0f), aspectRatio,
                1.0f, 10000.0f);
        }
        // Draw the mesh, using the effects set above.
        mesh.Draw();
    }
    base.Draw(gameTime);
}

And the FPS class:

public class FpsMonitor
{
    public float Value { get; private set; }
    public TimeSpan Sample { get; set; }
    private Stopwatch sw;
    private int Frames;
    public FpsMonitor()
    {
        this.Sample = TimeSpan.FromSeconds(1);
        this.Value = 0;
        this.Frames = 0;
        this.sw = Stopwatch.StartNew();
    }
    public void Update()
    {
        if (sw.Elapsed > Sample)
        {
            this.Value = (float)(Frames / sw.Elapsed.TotalSeconds);
            this.sw.Reset();
            this.sw.Start();
            this.Frames = 0;
        }
    }
    public void Draw(SpriteBatch SpriteBatch, SpriteFont Font, Vector2 Location, Color Color)
    {
        this.Frames++;
        SpriteBatch.DrawString(Font, "FPS: " + this.Value.ToString(), Location, Color);
    }
}

I tried in the Game1.cs to use it in the constructor:

fpsm = new FpsMonitor();
fpsm.Update();
fpsm.Draw(spriteBatch, fonts, new Vector2(5,5), Color.Red);

But thats not how to use it. How do i use it and where in my code ?

pinckerman
  • 4,115
  • 6
  • 33
  • 42
Doron Muzar
  • 443
  • 1
  • 10
  • 26

2 Answers2

2

From what I see

fpsm = new FpsMonitor(); // in constructor
fpsm.Update();// in update I think first line

spriteBatch.Begin();  // in draw Last lines probably even after base.Draw(gameTime);
fpsm.Draw(spriteBatch, fonts, new Vector2(5,5), Color.Red);
spriteBatch.End();

That should work like a charm

[Edit for spritefont explanation]

You will need to create a SpriteFont. To do that right click Content chose add new and create spritefont. It is an XML file that will be converted when you compile. you can change the font and height I suggest Arial and 10.... you can always change that.

Next you need to load it. I usually do it like this.

in the class

private Spritefont Arial10;

in the LoadContent

Arial10 = Content.Load<Spritefont>("Arial10");

Now you can do this

spriteBatch.Begin();  // in draw Last lines probably even after base.Draw(gameTime);
fpsm.Draw(spriteBatch, Arial10 , new Vector2(5,5), Color.Red);
spriteBatch.End();
user2888973
  • 583
  • 3
  • 15
  • user2888973 its thrwoing null exception on the FPS class on the line: SpriteBatch.DrawString(Font, "FPS: " + this.Value.ToString(), Location, Color); the variable Font is null – Doron Muzar Oct 20 '13 at 09:43
  • In the Game1.cs i guess i need to do something with the fonts variable. How do i use it ? – Doron Muzar Oct 20 '13 at 09:44
  • Is your `fonts` variable actually set to a valid `SpriteFont`? To load a font, inside `LoadContent()` use: `fonts = Content.Load("MyFont");` – Sarkilas Oct 20 '13 at 10:02
  • Modified my answer to include SpriteFont explanation – user2888973 Oct 20 '13 at 10:06
  • user2888973 ok i tried your code but once i try to change the font name in the SpriteFont i created in this line: ariel im getting an error when trying to compile:Error 1 The font family "ariel" could not be found. Please ensure the requested font is installed, and is a TrueType or OpenType font. C:\Users\bout0_000\Documents\Visual Studio 2010\Projects\MyFirst3D\MyFirst3D\MyFirst3D\MyFirst3DContent\SpriteFont1.spritefont MyFirst3D How do i install this font and others ? – Doron Muzar Oct 20 '13 at 10:15
  • it's Arial not ariel (I always forget that too) but you can input any font you have installed on your system. – user2888973 Oct 20 '13 at 10:18
  • No same error. I guess i didnt install any fonts on my system yet. I will have to check how to do it. im using windows 8. – Doron Muzar Oct 20 '13 at 10:22
  • Common there must be a font on your system.... just open Wordpad and see what fonts you have. – user2888973 Oct 20 '13 at 10:24
  • Right i saw what fonts i have so i selected for the test: Consolas. And the error is gone. But now when i try to run the program in Game1.cs in the line: Arial10 = Content.Load("Consolas"); i get error Error loading "Consolas". File not found. It does found it in the SpriteFont but it dosent find it in Game1.cs – Doron Muzar Oct 20 '13 at 10:30
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/39590/discussion-between-user2888973-and-doron-muzar) – user2888973 Oct 20 '13 at 10:32
0

You can't draw the FPS in the Initialize method. You need to draw in the Draw method, and update in the Update method. Your FPS will never draw if it doesnt draw it on the Draw method. Initialize is only called once ever, and your GraphicsDevice is cleared every single frame.

Within Game1.cs from the Initialize method, remove these lines:

fpsm.Update();
fpsm.Draw(spriteBatch, fonts, new Vector2(5,5), Color.Red);

Add fpsm.Update(); to the Update() method, and add this to your Draw method within Game1.cs (after GraphicsDevice.Clear(Color.CornflowerBlue);):

spriteBatch.Begin();
fpsm.Draw(spriteBatch, fonts, new Vector2(5,5), Color.Red);
spriteBatch.End();

I am pretty sure this is what you need to do.

Don't forget to load the font in the LoadContent() method by doing:

fonts = Content.Load<SpriteFont>("MySpriteFont");

Also the spritefont needs to be a compiled file from your contents project! Just right-click on the content project, select Add > New Item and choose a SpriteFont file.

Sarkilas
  • 76
  • 7