Frame Rate Independant Aplication

  • obito1406
    Likes 0

    Problem Description

    Hi I come from the Flappy Bird Course using SFML from udemy. This its not  a problem but an explanation I required here.

    On the main Game.cpp where everything its handle we have this code:

    void Game::Run()
    	{
    		float newTime, frameTime, interpolation; //frameTime
    		float currentTime = mClock.getElapsedTime().asSeconds();
    		float accumulator = 0.0f;
    
    		while (mData->window.isOpen())
    		{
    			//1.handle events and changes
    			mData->machine.ProcessStateChanges();
    
    			newTime = mClock.getElapsedTime().asSeconds();
    
    			frameTime = newTime - currentTime; //The time that took a frame to be executed
    
    			if (frameTime > 0.25f)
    			{
    				frameTime = 0.25f;
    			}
    
    			currentTime = newTime;
    			accumulator += frameTime;
    
    			while (accumulator >= dt)
    			{
    				mData->machine.GetActiveState()->HandleInput();
    				mData->machine.GetActiveState()->Update(dt);
    
    				accumulator -= dt;
    			}
    
    			interpolation = accumulator / dt;
    			mData->machine.GetActiveState()->Draw(interpolation);
    		}
    	}

    I would like some detail explanation on the frame mathematics here.

    I do understand that our while()  here its executed once every frame or at least thats what we want to achieve here.

    So we calculate the time between frames as the difference of time between the previous call to our while() and the next one the while() its call.

    Once the frameTime has been calculated, we check if frameTime > 0.25 and if so its set to 0.25...¿why its this done? I guess its to set a limit but no clue.

    Then theres the accumulator and the while (accumulator > dt). dt its 1/60 which its the time that takes 1 frame to be executed at 60 fps.

    I dont understand this part too well. An example to understand it would be great.

    Thank you

     

     

  • Sonar Systems admin
    Likes 0

    No problem at all.

    while is executed every frame, this is always the case but time difference between frames or the number in a second isn’t always fixed and this is what we try to keep consistent, you probably have heard 60fps is a good target.

    The limiter to 0.25 is there to prevent it from getting to big and objects having unexpected behaviour due to some sudden fps drop.

    Accumulator just tracks the total time passed.

    Hope this helps,, if you have anymore questions feel free to post them on here.

  • Sonar Systems admin
    Likes 0

    Here is a really useful link to help learn more about this https://gafferongames.com/post/fix_your_timestep/ 

  • obito1406
    Likes 0

    Thanks for the response Ill give it a read to the link you provide. Seems truly interesting

  • Sonar Systems admin
    Likes 0

    :D          

Login to reply