c++frame-rategame-loop

How to make timer for a game loop?


I want to time fps count, and set it's limit to 60 and however i've been looking throught some code via google, I completly don't get it.


Solution

  • You shouldn't try to limit the fps. The only reason to do so is if you are not using delta time and you expect each frame to be the same length. Even the simplest game cannot guarantee that.

    You can however take your delta time and slice it into fixed sizes and then hold onto the remainder.

    Here's some code I wrote recently. It's not thoroughly tested.

    void GameLoop::Run()
    {
        m_Timer.Reset();
    
        while(!m_Finished())
        {
            Time delta = m_Timer.GetDelta();
            Time frameTime(0);
            unsigned int loopCount = 0;
    
            while (delta > m_TickTime && loopCount < m_MaxLoops)
            {
                m_SingTick();
                delta -= m_TickTime;
                frameTime += m_TickTime;
                ++loopCount;
            }
            m_Independent(frameTime);
    
            // add an exception flag later.
            // This is if the game hangs
            if(loopCount >= m_MaxLoops)
            {
                delta %= m_TickTime;
            }
    
            m_Render(delta);
            m_Timer.Unused(delta);
        }
    }
    

    The member objects are Boost slots so different code can register with different timing methods. The Independent slot is for things like key mapping or changing music Things that don't need to be so precise. SingTick is good for physics where it is easier if you know every tick will be the same but you don't want to run through a wall. Render takes the delta so animations run smooth, but must remember to account for it on the next SingTick.

    Hope that helps.