The MonoGame Update() Cycle
By Stephen Armstrong // October 26, 2019
An introduction to MonoGame’s Update cycle.
Moving your character, collision detection, timers, enemy AI, and much more – MonoGame’s Update() cycle is where the magic happens in your game.
By default, your game will try to run the Update() in Game1.cs sixty (60) times a second. It may not be a perfect sixty, and will be impacted if you run excessive tasks (especially nested loops).
Starting Update() code
The following is the default starting Update() code in a new MonoGame project:
protected override void Update(GameTime gameTime)
{
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape))
Exit();
// TODO: Add your update logic here
base.Update(gameTime);
}
The first line is basic input handling. If you press on an XInput controller or Escape on your keyboard the game will close.
The easiest way to demonstrate the Update() cycle is to add the following line:
System.Console.WriteLine(gameTime.ElapsedGameTime.TotalMilliseconds);
This code will output the total milliseconds that have passed since the previous Update().
If you run your game and check the Output, it will read “16.6667” – which roughly equals one sixtieth of a second (if the Output does not appear, click View > Output to display it).
Create a basic timer
Add a float called timer to Game1:
public class Game1 : Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
// timer stores accumulated milliseconds
float timer;
Now go to the Update() and add the following code:
// Add elapsed milliseconds to timer. TotalMilliseconds is a double so must be cast to a float
timer += (float)gameTime.ElapsedGameTime.TotalMilliseconds;
// Display the timer in the Output
System.Console.WriteLine("Timer: {0}", timer);
If you run your game now, you will see the timer counting up every millisecond in the Output.
Further reading
Future tutorials will include examples of how to use the Update() cycle for input handling, animation, collision detection, and updating other classes/objects within your game.