How To: Make a Game Use a Variable Time Step

Demonstrates how to make a game use a variable time step.

The Complete Sample

The code in this tutorial illustrates the technique described in the text. A complete code sample for this tutorial is available for you to download, including full source code and any additional supporting files required by the sample.

To Make a Game Use a Variable Time Step

  1. Create a class that derives from Game.
  2. Set IsFixedTimeStep to false. This causes Update to be called as often as possible instead of being called on a fixed interval.

    this.IsFixedTimeStep = false;
  3. Since the amount of time between calls to Update will vary, specify any rates used in the game as units per millisecond (ms).

    // Speed in world units per ms.
    private double speed = 0.02f;
  4. In Update get the value of gameTime.ElapsedGameTime.TotalMilliseconds. This gives the amount of time that has passed since the last call to Update.

    // Time elapsed since the last call to update.
    double elapsedTime = gameTime.ElapsedGameTime.TotalMilliseconds;
  5. Determine the change that occurred since the last update by multiplying any rates being used by the elapsed time.

    // Multiply speed by elapsed time to get the distance moved.
    double distance = (speed * elapsedTime);

Community Additions