gameprogcpp/code

Chapter 1 - Implementation of Game::Update()

Closed this issue · 1 comments

First of all thank you for the excellent book.
I was wondering if the implementation of the Game::UpdateGame() in Chapter 1 on page 26 is affected by the different SDL_GetTicks() calls? If I am correct those calls will result in a slightly different number of ticks during the execution of UpdateGame().

This could in easily be solved by adding a local variable storing the result of the call at the begin of UpdateGame():

void Game::UpdateGame()
{
    // Compute delta time
    Uint32 now = SDL_GetTicks(); // call SDL_GetTicks() only once
    
    // Wait until 16ms has elapsed since last frame
    while (!SDL_TICKS_PASSED(now, mTicksCount + 16))
        ;

    float deltaTime = (now - mTicksCount) / 1000.0f;
    if (deltaTime > 0.05f)
    {
        deltaTime = 0.05f;
    }
    mTicksCount = now;
}

You have to do the repeated SDL_GetTicks calls because of the way SDL_TICKS_PASSED works. It's basically just a comparison saying is the value from the first parameter greater than the value of the second.

Also in this specific case, SDL_GetTicks returns millisecond resolution so you wouldn't get a different number from when the while loop ends and you get to the line that calculates deltaTime.