首页 > 解决方案 > C++ 中的处理时间

问题描述

我正在编写一个模拟程序。我在处理时间时遇到了一些困难。

我的程序有一个时间段和一个总经过时间变量。我有交通灯对象。当经过的时间是周期的整数倍时,我想更改它们的颜色。例如,总时间从 0 开始,在 60 秒内结束,周期为 10 秒。因此,当时间为 10、20、30 等时,应更改颜色。

我尝试使用简单的数学来解决这个问题,但是当我绘制对象时没有任何改变。那么,我该如何处理改变颜色的时间呢?

标签: c++timesfml

解决方案


您可以使用标准<chrono>库,但 SFML 有自己的一套工具来处理时间。您不需要任何复杂的计算或线程。您需要的部分内容的简化示例:

#include <SFML/Graphics.hpp>
#include <vector>

class Light : public sf::CircleShape {
public:
    Light(std::vector<sf::Color> cols, sf::Time period) 
        :colors{ cols }, colorIdx{ 0 }, changePeriod{ period }
    {
        setRadius(100);
    }

    void update(sf::Time deltaTime) {
        elapsedTime += deltaTime;
        while (elapsedTime >= changePeriod) {
            elapsedTime -= changePeriod;
            changeColor();
        }
        setColor();
    }
protected:
    void changeColor() {
        if (++colorIdx == colors.size()) {
            colorIdx = 0;
        }
    }

    void setColor() {
        setFillColor(colors[colorIdx]);
    }
private:
    std::vector<sf::Color> colors;
    std::size_t colorIdx;
    sf::Time changePeriod;
    sf::Time elapsedTime;
};

int main() {
    Light light1({sf::Color::Red, sf::Color::Yellow, sf::Color::Green}, sf::seconds(1));

    Light light2({sf::Color::Red, sf::Color::Green}, sf::milliseconds(200));
    light2.setPosition(300, 300);
    light2.setRadius(20);

    sf::RenderWindow window(sf::VideoMode(400, 400), "");
    sf::Event event;
    sf::Clock clock;

    while (window.isOpen()) {
        while (window.pollEvent(event)) {
            if (event.type == sf::Event::Closed) window.close();
        }

        sf::Time dt = clock.restart();
        light1.update(dt);
        light2.update(dt);

        window.clear();
        window.draw(light1);
        window.draw(light2);
        window.display();
    }
}

推荐阅读