#3: Time based movement for game objects
By Peter Stuifzand
Time based movement is used in games to fix the problems that occur when using different computer speeds. All movement and events will be timed using real 'clock' time.
Introduction
For a game to be good it should have the same movement speed on every computer. There are older games that will run very quick on newer computers. This is not very nice and we don't want it. A game should run at the same speed on every computer.
There is a simple way to get behaviour. On the start of every frame the number of elapsed milliseconds should be calculated. All movement should be based on this number.
Milliseconds are what we need
First we need a function that will give us the number of milliseconds. Most functions that do this will gives us the number of milliseconds since an arbitrary time. Mostly these will be counted from the start of the program, or from the starting of the computer.
Actually it doesn't really matter what kind of unit you use for the calculation of the elapsed frame time. I use seconds or milliseconds, because it's easier calculate the speed of the game objects.
I will show with the function SDL_GetTicks how this
works. SDL_GetTicks documentation.
SDL_GetTicks
SDL_GetTicks returns the number of milliseconds since library
initialization.
Uint32 start = SDL_GetTicks();
Uint32 end=start;
for (;;) {
do {
end = SDL_GetTicks();
} while (start==end);
Uint32 frame_time = end-start;
start = end;
// calculate movement based on frametime.
}
By specifying the speed of units gameunits/milliseconds you can
control how much a unit moves in the game. The frame_time in the
above example is the number of milliseconds that have elapsed since
the previous frame.
Speed of objects
The objects in your game will have a speed or some other function that'll specify their movement. For a player object that is moved with that cursor keys it is fairly simple to calculate its position in a speed safe way.
game_object_t player = { 0, 0 };
player.x += frame_time * PLAYER_SPEED * dir_x;
player.y += frame_time * PLAYER_SPEED * dir_y;
If the player can only move left and right then dir_x would be -1
or 1 to specifiy it direction or 0 to have it stop. The position
of the player can be calculated by this. For a more complex user
defined movement pattern on could use sin and cos to calculate the
direction.
Conclusion
By using a time based movement based main loop, you are able to get nice movement for all objects in your game. The speed of all objects also is the same on all computers independent of it's speed.