Search code examples
c#xnamonogamexna-4.0

GameTime is always 0 - MonoGame (XNA) - C#


Currently, my sprites loop at the same speed that MonoGame loops through it's code. I want to slow this process down by creating a delay using GameTime. It never worked, however, so I decided that I would use debug.WriteLine() to check if GameTime updated. It didn't, ever.

abstract class Entity
{
    protected GameTime _gameTime;
    public TimeSpan timer { get; set; }

    public Entity()
    {
        _gameTime = new GameTime();
        timer = _gameTime.TotalGameTime;
    }

    public void UpdateTimer()
    {
        timer += _gameTime.TotalGameTime;
        Debug.WriteLine("Timer: " + timer.Milliseconds);
    }
}

UpdateTimer() runs continously in the game loop, but always writes "0" in the debug output.

What am I doing wrong? Or is there a better way to do this?


Solution

  • Your _gameTime is 0 because it is just initalized, thats it.

    Your Game class (which inherits from Game) got an Update method, with the parameter type GameTime. This parameter is your current frametime. So your UpdateTimer should have also an GameTime parameter and should be called in your Game.Update

    public void UpdateTimer(GameTime gameTime)
    {
        timer += gameTime.ElapsedGameTime;
        Debug.WriteLine("Timer: " + timer.TotalMilliseconds);
    }