Take the 2-minute tour ×
Game Development Stack Exchange is a question and answer site for professional and independent game developers. It's 100% free, no registration required.

I am having trouble making my game's main loop to run at exactly N fps. Let's say i want game to run at constant 60 fps. Here is part of my code:

int ticksPerSecond = 60;
int skipTicks = 1000 / ticksPerSecond;
int maxFrameskip = 10;

// ...

while(true)
{
    loops = 0;
    while (Environment.TickCount > nextGameTick && loops < maxFrameskip)
    {
        OnUpdate();
        nextGameTick += skipTicks;
        loops++;
    }

    Render();
}

As a result i am getting around 64 fps, not 60. Why is that and what am i doing wrong here?

share|improve this question

1 Answer 1

You will have a rounding error.

(int)(1000 / 60) = 16 
1000 tickspersecond / 16 ticksperframe = 62.5 framespersecond 
// forgive my horrible units

Also, it looks like you abort your loop when you hit 10 updates. Is your update so fast that that ever happens?

share|improve this answer
    
Currently i am getting around 3000 fps without any limiting. –  Skull Aug 19 '12 at 7:28
2  
I don't think I know enough about the context of your question. I tried to give you the only answer I could. To me, it looks like your code draws as often as it can, and only limits its calls to update. That seems backwards if you are trying to fix your frames per second. Can you elaborate what your OnUpdate() and Render() functions do? –  Seth Battin Aug 19 '12 at 16:56
    
OnUpdate function handles AI, input and other stuff, while Render draws everything on the screen. Nothing extraordinary. –  Skull Aug 20 '12 at 3:49

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.