c++ - C++ 中的处理时间
问题描述
我正在编写一个模拟程序。我在处理时间时遇到了一些困难。
我的程序有一个时间段和一个总经过时间变量。我有交通灯对象。当经过的时间是周期的整数倍时,我想更改它们的颜色。例如,总时间从 0 开始,在 60 秒内结束,周期为 10 秒。因此,当时间为 10、20、30 等时,应更改颜色。
我尝试使用简单的数学来解决这个问题,但是当我绘制对象时没有任何改变。那么,我该如何处理改变颜色的时间呢?
解决方案
您可以使用标准<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();
}
}
推荐阅读
- swift - 在 Swift 中显示来自 Parse 的图像
- javascript - UrlSearchParams.get() 不适用于重写的 url
- php - Symfony 3.4 表单小部件以捆绑名称为前缀
- jupyter-notebook - Jupyter Notebook 有文件重命名挂钩吗?
- c++ - 必要时违反组合优于继承可以吗?
- javascript - 应该如何为 HTML 画布旋转鼠标事件?
- arrays - 为什么将数组作为道具传递时会转换为对象?
- python-3.x - 类对象名称未定义
- amazon-web-services - 模板资源块中未解决的资源依赖项 [arn:aws:s3:::alberto313131/*]
- json - 实时数据搜索问题,如何通知用户更具体的搜索