How would I go about fixing my variable rate SDL timestep?

283 views Asked by At

I my gameloop is going around 10x faster than what it should be and I have no idea how to fix it.

I tried multiple different other variable rate timesteps but none seem to be as effective as this one.

int main(int argc, char* args[])
{
    Uint32 t = 0;
    Uint32 dt = 10000 / 60.0;

    Uint32 currentTime = SDL_GetTicks();

    game = new Renderer();

    game->init("window", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 800, 600, false);

    while(game->running()){
        
        Uint32 newTime = SDL_GetTicks();
        Uint32 frameTime = newTime - currentTime;
        currentTime = newTime;

        while(frameTime > 0.0)
        {
            float deltaTime = std::min(frameTime, dt);
            game->handleEvents();
            game->update(deltaTime/1000);
            frameTime -= deltaTime;
            t += deltaTime;
            
            t += dt;
        }
        game->render();
    }

    game->clean();

    return 0;
}

Whenever I call

g.transform.position.x+=1/60.0;

in the render function, I expect it to move 1 pixel every 1 second but it moves way to fast. Does anyone know how I can slow this down or what I'm doing wrong?

1

There are 1 answers

0
Kolbjørn On

It goes too fast because you update your object in the render method. You have a mix of fixed and variable timestep which will try to catch up if the physics part of your game lags behind, but no restriction on the render method. (which is good)

So you should update your game objects in your update method and then set your object to g.transform.position.x+=deltatime (you probably want another variable in here later, example: g.transform.position.x+=speed*deltatime)

All you should do in game->render() is to draw your object.

This should fix your gameloop timing.

Only reason to render your object at a different position in game->render() would be if you have a fixed timestep in your update method so that you would have to render in between update cycles.

Hope this helps.