I want my game run at 60 fps, but i don't know where to start, i have the simple loop:
How do i lock the fps to 60?
Depends what you mean by saying "you want to lock the game at 60fps".
If you want to limit the game rendering at max 60fps its very simple :
Each frame, just check if the game is running to fast, if so just wait :
Please note that if vertical sync is enabled, rendering will already be limited to 60fps.
But if you want to have your game logic locked at 60fps, no more no less, that's different. Then you have to separate code you want to run at 60fps from rendering code and make necessary changes to make sure that code is called at same fixed time intervals. It is called "fixed timestep". Make a search on gamedev or google. There is a lot of info on this.
EDIT : as Roy T. pointed out, code is not guaranteed to works because
|show 1 more comment|
Sleep is a very bad idea for the reasons already pointed out - the only justifiable case to use it is for saving battery on mobile devices.
If you want to lock to 60 fps one way would be to measure the time that's elapsed since the last frame ran; if that equals or exceeds (1.0 / 60.0) seconds then run a frame. Of course you'll need a high resolution timer to get this right, and of course it's a busy-wait loop that will chew up CPU time, but it works.
(You might even find some useful work to do during that busy-wait period, such as updating dynamic resources or whatever).
Another way is to use vsync. Most monitors nowadays will run at 60hz, and those that don't are extremely likely to support it, so just enable vsync, set your refresh rate if needed, and run as normal.
Do you want to synchronize on vsync ? There are differents solutions depending on your platform. Search vsync on google. On directx, you can limit on fullscreen app with D3DPRESENT_INTERVAL_ONE or use WaitForVerticalBlank on windowed app.
Look this article
If you are measuring time you also really need to be using QueryPerformanceCounter as timeGetTime jumps in large increments.
There is a fairly involved blog post on the subject of windows timing:
Also, if there are no other threads needing to work Sleep(0) will return immediately, you need to use SwitchToThread, and if that 'fails' call Sleep with a non-zero amount instead to actually go to sleep.
That said, I would still recommend using the vsync features, as that can be turned into a kernel wait on an interrupt behind the scenes and also context switch out properly while waiting, much like the sleep. Also, sleeping is a bit odd of a thing to do as you dont actually know when the vsyncs really occur, even with vsync enabled, so it is hard to sleep a proper amount and not miss the vsync on the next frame in a lot of cases (esp if youre CPU overhead is pushing 15+ milliseconds)