2

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?

MyNameIsGuzse
  • 273
  • 1
  • 5
  • 23
  • 2
    General note: You should (almost) always use the `Total_` properties (`TotalSeconds`, `TotalMilliseconds`, ...) when dealing with `GameTime`. The "non-Total" methods return only that *part* of the time, while the "Total" ones return the entire span expressed as the time unit you want. For example, if 1.7 seconds pass, `Milliseconds` will return `700`, while `TotalMilliseconds` will return `1700`. `Seconds` will return `1`, and `TotalSeconds` will return `1.7`. Generally, the only time to use the "plain" properties is when you want to do special formatting, or something else non-standard. – Bradley Uffner Oct 12 '17 at 12:31
  • 1
    Also note, you don't actually need to keep your own accumulated timer, `GameTime` already does that for you, in the [`GameTime.TotalGameTime`](https://msdn.microsoft.com/en-us/library/microsoft.xna.framework.gametime.totalgametime.aspx) property. – Bradley Uffner Oct 12 '17 at 12:33

2 Answers2

3

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);
}
DogeAmazed
  • 858
  • 11
  • 28
  • 1
    Don't use `Milliseconds`! Use `TotalMilliseconds`. `Milliseconds` waps every 1000 ms (if `1500` ms pass between updates, it will only return `500`). `TotalMilliseconds` will give you the time since last update expressed completely in milliseconds. – Bradley Uffner Oct 12 '17 at 12:22
  • 1
    Just copied it from him, so yeah.. I can fix it. – DogeAmazed Oct 12 '17 at 12:45
1

You need to pass the main gameTime to the Entity. ex-(Entity._gameTime = gametime) Then it will start updating.

John Thompson
  • 386
  • 3
  • 10