0

I want to build a small engine in SDL2 c++ and right now I'm in the process of calculating deltaTime so I've tried and researched a lot and this code should actually be the correct calculation but I must have done something wrong because the value is always wrong, so when i do a playermovement with it it's frame dependent how fast it is, although i calculate it with the deltatime.

The game loop

    SDL_Event event;
    int frameCount = 0;
    long startTime = SDL_GetTicks();
    long frameStart, frameTime;

    auto prevTime = std::chrono::high_resolution_clock::now();

    while (!quit){
        auto currentTime = std::chrono::high_resolution_clock::now();
        std::chrono::duration<double> deltaTime2 = currentTime - prevTime;
        prevTime = currentTime;
        deltaTime = deltaTime2.count();

        frameStart = SDL_GetTicks();

        while (SDL_PollEvent(&event)){
            if (event.type == SDL_QUIT)
                quit = true;
            UpdateInput(event);
        }

        UpdateGameObjects();

        if (capFPS){
            frameTime = SDL_GetTicks() - frameStart;
            if ((1000 / maxFPS) > frameTime) {
                SDL_Delay((1000 / maxFPS) - frameTime);
            }
        }

        frameCount++;
        float elapsedSeconds = (SDL_GetTicks() - startTime) / 1000;
        if (elapsedSeconds >= 1) {
            int currentFPS = frameCount;
            text->SetText(std::to_string(currentFPS).c_str());
            frameCount = 0;
            startTime = SDL_GetTicks();
        }
    }

PlayerMovement

SetSurfacePos(gameObject->surf, gameObject->surf->rect->x + (555 * deltaTime), gameObject->surf->rect->y);

please can someone help?

I've tried several things, giving the code to other places in the looop, changing the variable type, even a completely new calculation, but all without success

Nagisa
  • 9
  • 1
  • Don't use `high_resolution_clock`. It's not guaranteed to be monotonic and it can refer to different clocks on different platforms or with different compilers. See the notes at https://en.cppreference.com/w/cpp/chrono/high_resolution_clock – Jesper Juhl Aug 03 '23 at 23:10
  • 1
    Does this help? https://stackoverflow.com/a/59446610/576911 – Howard Hinnant Aug 04 '23 at 00:12

0 Answers0