A Tick based Game Loop in C#
Posted on 16.08.2009 03:59 pm
As a practice program in C# I did a little Tick based Game Loop. You can grab the source here if you're interested.
A Tick based Game Loop uses a fixed number of Ticks per draw. So it will update the game information and process the user input as fast as possible but only draw to the screen when a certain number of ticks is hit and then reset that count.
A basic (naive) Game Loop is like this.
while(true)
{
ProcessUserInput();
UpdateGameState();
DrawToTheScreen();
}
The issue with a game loop that works this way is that you are trying to draw as fast as the computer can loop. Many very old games have this kind of a loop and when run on a modern machine the games are unplayable due to the machine's speed.
A Tick based Game Loop is something like this.
MaxNumberOfTicks = (some number);
while(true)
{
ProcessUserInput();
UpdateGameState();
ticks = GetTickCount();
if(ticks > MaxNumberOfTicks)
{
DrawToTheScreen();
ResetTicks();
}
}
This is a better approach and good enough for simple single player games. In this kind of a game loop you are able to Process the user input and update the game state as fast as the computer can loop but the drawing to the screen is relatively stable.
Example output of the game loop:
Game Updates 500
Draw Count 480
Frames per second 68.3673143149452
This means it has done 480 draws to the screen and between draw 479 and 480, it looped 500 times to update the game.
And it's running at a smooth 68 FPS (based on the draw count and milliseconds from game start).
It runs both on Visual C# 2008 and Mono.
Hopefully it's useful to someone out there :)
1 6 Like it or hate it? - Comment (2)
AC
0 0 / Posted on 14.11.2009 07:11 pm
If you move objects around in UpdateGameState() then they will still be moving too fast on really powerful computers unless you do something like this:X = X + TicksSinceLastFrame / 1000 * Velocity;
Pod
0 0 / Posted on 03.01.2010 01:59 am
>The issue with a game loop that works this way is that you are trying to draw as fast as the computer can loop. Many very old games have this kind of a loop and when run on a modern machine the games are unplayable due to the machine's speed.Not only does your game loop have this problem, but it has a worse problem: on a 400ghz machine, your frames will only be updating 70hz (or whatever), but your game logic will be going at max speed, which will probably be 1GZ logic updates per frame :P
You won't even be able to see what's going on!
Process time: 0.009599 seconds