Doing Something every few milliseconds

I'm doing a game, and I want to update the x and y offsets (integers) of my player image every few seconds or so by the hspeed and vspeed. Sort of like:
1
2
3
4
5
6
if (player.hp>0)
{
    //handle movement (I want to do this every 100 milliseconds or so)
    player.x = player.x+player.hspeed;
    player.y = player.y+player.vspeed;
}

How would I do this?
The most common system for game movement is to split updates into "frames" (named so because you do one update per draw, so one update per frame).

Typical game loops look something like this:

1
2
3
4
5
6
7
8
9
10
11
12
while(game_is_running)
{
  Process_user_input_and_stuff();

  Update_all_game_objects();

  Draw_the_world();

  Display();

  Wait_for_next_frame();
}


In this type of system, Update_all_game_objects would be called once per frame. If you are running at 60 fps, that means one update every 17 or so ms.




Of course... if you're asking how to do this in the console... don't bother. See this:
http://cplusplus.com/forum/articles/28558/
That is almost exactly what my loop looks like. I'm only missing the Wait_for_next_frame(). What would be a good way to do this?

EDIT: I'm assuming it's probably something about the framerate. Let's say I want to cap it at 60.
Last edited on
Writing a [good] framerate regulator can be tricky.

Here's one I prepared earlier:

http://nesdev.parodius.com/bbs/viewtopic.php?p=57398#57398
Some comments, handled in Disch link :
On windows at least, you wan't wait for a fixed number of ms precisely, depending on the task scheduler. On my computer, time slices are about 15ms, so i can't do pauses of 17ms exactly for example.
In that case, you must have a sleep() in your loop, and at each iteration, see if the time elapsed since the last frame refresh is at least the period wanted between frames.
You must also handle the case where the program is slower than expected (for hardware or software reasons). So you must also test if the elapsed time since the last refresh is superior to the period between 2 frames, and in that case update your game status for that number of frames before refreshing. That will guarantee that the games stays at the same visible speed, at the cost of missed frames. if you don't do that, your game animation will slow down when the computer takes more time to execute each frame thatn the wanted period between frames
Topic archived. No new replies allowed.