Game Development Reference
In-Depth Information
happen if a part of the game is very resource-hungry. We can retrieve this informa-
tion using the IsRunningSlowly property. If the game is running slowly, we can for
example decide to temporarily switch off or simplify a part of the game code.
18.3.1 Other Useful Classes for Managing Time
Next to the GameTime class, another important type is the TimeSpan struct. For ex-
ample, the ElapsedGameTime property in the GameTime class returns a TimeSpan ob-
ject. The TimeSpan struct is very useful for representing a time interval, such as the
time passed since the last update. You can retrieve the time information from the
TimeSpan object in a variety of ways: in hours, seconds, minutes, or 'ticks'. A tick
is a time unit used by a computer, and at the same time it is the smallest time unit
that a computer can measure. One tick stands for 100 nanoseconds. We can retrieve
the time interval size in ticks using the Ticks property.
Just like the GameTime class, the TimeSpan struct cannot represent dates such as
'June 8, 1977'. To express a moment in time, we use another struct called DateTime .
This struct has a number of useful ways to deal with dates. There are easy ways to
retrieve the month, year or day, and we can use the DateTime type to format the date
as a string. For example, if we want to format the total elapsed game time as a string
containing the passed time in minutes and seconds, we can do this as follows:
DateTime gameTime = new DateTime(gameTime.TotalGameTime.Ticks);
string passedTime = gameTime.ToString("mm:ss");
You can see that each time-related class or struct has its own pros and cons. Watch
this when you are using these classes, and be sure to use the right class for the right
job!
18.3.2 A Timer for Controlling Visibility of a Game Object
What we are going to do in this section is create a class that controls the visibility of
a game object based on a timer. Let us call this class VisibilityTimer . The idea of this
class is that we can assign it a target game object, of which it will set the visibility to
false by default, but when we start the timer, the target object becomes visible until
the timer has reached its maximum value. We can then use such a timer and connect
it to an overlay in order to show that overlay on the screen for a while. The complete
VisibilityTimer class is given in Listing 18.1 .
A visibility timer object needs to keep track of a couple of things. For one, we
need to store the target object of which we are going to control the visibility. Also,
we will store how much time in total this object should be visible for when the
timer is started. Finally, when the timer is running we have to maintain how time is
Search WWH ::




Custom Search