DirectXTutorial.com
The Ultimate DirectX Tutorial
Lesson 5:  Building a Basic Timer
Log In
Lesson Overview

Timing in a game is absolutely vital.  Your game, whether you like it or not, will slow down and speed up seemingly at random.  As another program stops running a resource-consuming operation, your game will suddenly speed up, possibly confusing your player and spoiling the game.

This lesson will cover a simple technique to holding your game's speed to a constant rate.

Building the Timer

Because of the complexity of an advanced timer, such as one used in multiplayer games, we will start off with a very simple timer that limits the framerate to a specific quantity.  For our program, we will use 1/40th of a second (or 25 milliseconds per frame) as a limit to our framerate.

This basic timer is actually quite simple, and only consists of two lines of code:

// find out the starting time of each loop
DWORD starting_point = GetTickCount();

// check PeekMessage(), render a frame, etc.

// wait until 1/40th of a second has passed
while ((GetTickCount() - starting_point) < 25);

There really isn't much to go over here, as it is mostly just simple C++ code with a function in the middle.  Let's start by finding out what that function is.

GetTickCount();

GetTickCount() is a function that returns the number of milliseconds that have elapsed since Windows started.  Of course, that doesn't immediately seem useful, but if we can store the current tick-count now, then once we're done rendering we can check to see how many milliseconds have gone by, and wait until its time to run the next loop.

DWORD starting_point = GetTickCount();

So how does this all fit together?  We have as our first step, creating a DWORD called starting_point.  We will initialize this with the return value of GetTickCount().  We will then check PeekMessage(), handle any messages and render A SINGLE FRAME.  Once this frame is rendered, we get to our next statement:

while ((GetTickCount() - starting_point) < 25);

Now we check to see how many milliseconds have elapsed during the message handling and frame rendering.  Most likely, it was less than 25, and so our program just continues to re-check the elapsed time until 25 milliseconds have gone by.

Implementing the Code

Let's add this new code to the program we've been working on.  Below you see the updated program with the latest additions in bold.

[Show Code]

Summary

I'd say we're doing a fairly good job.  You now have under your belt all the Windows programming tools you will need for game programming.  With what you know, you can create a window, prepare it for a game, and have everything ready for the DirectX code.

So, now the real fun begins!  Let's dive into DirectX and build ourselves a 3D game!

Next Tutorial:  Direct3D Basics

GO! GO! GO!