Log in Page Discussion History Go to the site toolbox

XNA Tutorials/Keeping time

From BluWiki

Keeping Time in XNA

Written by Benjamin Hale

Part of a series of XNA Tutorials.

Variables

One must create variables to keep track of time. In this case, Int64 objects and a float are used:

Int64 seconds;
Int64 milliseconds = 0;
float interval = 1000f;

The interval is the amount of time one wishes to calculate. In this example, it is seconds being tracked, so the interval is set to 1000 milliseconds. One could add another variable for minutes if so desired.

The Update() Function

Update() is called 60 times per second as a default. The TotalMilliseconds property is the elapsed time since the last call to Update().

When milliseconds reaches a count of 1000 or greater, seconds is increased by one and milliseconds is reset to zero:

milliseconds += (long)gameTime.ElapsedGameTime.TotalMilliseconds;
if (milliseconds >= interval)
{
    seconds += 1;
    milliseconds = 0;
}

Were one calculating minutes, one would check to see if seconds was equal to 60, and if so, increase the minute variable by one and reset seconds to zero.

Displaying Time

When one makes a call to the DrawString() function, one cannot simply display an Int64 object to the screen (or any object, for that matter). One must call the objects ToString() method:

spriteBatch.DrawString(fonts[fontIndex], (seconds.ToString() + "." + milliseconds.ToString()), new Vector2(550.0f, 10.0f), randColor);

One could add the minutes to the string if one wished.

References

Microsoft, MSDN Library, January 2009

Site Toolbox:

Personal tools
GNU Free Documentation License 1.2
This page was last modified on 10 September 2009, at 18:41.
Disclaimers - About BluWiki