除了我的代码之外,还有什么原因会加速 chrono Time 吗?

Any reason chrono Time would be speeding up other than my code?

进入我的游戏几秒钟后,一切都在加速。我找不到我的代码有任何问题,但肯定有问题。我想知道我的显卡是否有可能进入高速档或其他原因。任何建议将不胜感激,谢谢!

#include <SFML/Graphics.hpp>
#include <iostream>
#include <chrono>
#include <ctime>    
#include "PongGame.h"

int main()
{

    PongGame game(10);
    sf::RenderWindow window(sf::VideoMode(1500, 900), "SFML works!");

    float UPDATE_INTERVAL = 900000000.0f;
    float lag = 0.0f;

    typedef std::chrono::high_resolution_clock Time;
    typedef std::chrono::milliseconds ms;
    typedef std::chrono::duration<float> fsec;
    auto prevTime = Time::now();

    while (window.isOpen())
    {
        auto currTime = Time::now();
        fsec fs = currTime - prevTime;
        ms d = std::chrono::duration_cast<ms>(fs);
        lag += d.count();
        //std::cout << "lag1: " << lag << "\n";
        while (lag > UPDATE_INTERVAL) {
            std::cout << "loop";
            sf::Event currEvent;
            while (window.pollEvent(currEvent))
            {
                if (currEvent.type == sf::Event::Closed) { window.close(); }
            }
            game.PollKeys();
            game.Update(1.0f);
            game.Render(1.0f, &window);
            //lag -= UPDATE_INTERVAL;
            lag = 0;
            std::cout << "lag2: " << lag << "\n";
        }
    }

    return 0;
}

@Howard Hinnant

我现在正在根据计时毫秒来比较所有内容。我现在已经逐步完成了代码,但我只是不明白为什么它会像现在这样加速。这是新代码:

#include <SFML/Graphics.hpp>
#include <iostream>
#include <chrono>
#include <ctime>    
#include "PongGame.h"

int main()
{
    typedef std::chrono::high_resolution_clock hiResTime;
    typedef std::chrono::milliseconds ms;
    typedef std::chrono::high_resolution_clock::time_point time_point;

    PongGame game(10);
    sf::RenderWindow window(sf::VideoMode(1500, 900), "SFML works!");
    time_point prevTime = hiResTime::now();
    time_point currTime = hiResTime::now();
    const ms UPDATE_INTERVAL(99999999);
    ms lag(0);

    while (window.isOpen())
    {
        prevTime = currTime;
        time_point currTime = hiResTime::now();
        ms currInterval = std::chrono::duration_cast<std::chrono::milliseconds>(currTime - prevTime);
        lag += currInterval;
        if (lag > UPDATE_INTERVAL) {
            //std::cout << "loop";
            sf::Event currEvent;

            if ((window.pollEvent(currEvent)) && (currEvent.type == sf::Event::Closed)) { window.close(); }
            game.PollKeys();
            game.Update(1.0f);
            game.Render(1.0f, &window);

            //lag -= UPDATE_INTERVAL;
            lag = ms(0);
        }
    }
    return 0;
}

在旧版本的代码中,您忘记更新 prevTime。在当前版本中,您仍然不会这样做,因为 prevTime = currTime; 中的 currTime 是直接在 main() 中定义的那个,但它永远不会更新,因为 time_point currTime = hiResTime::now(); 定义了新变量使用相同的名称(这是允许的,因为它在嵌套块中)而不是更新先前定义的名称。所以第一个 currTime 总是包含游戏开始时间。