Skip to content

Instantly share code, notes, and snippets.

@eXpl0it3r
Created August 26, 2023 17:03
Show Gist options
  • Save eXpl0it3r/ab64f517afc135449c7008fbdf639b29 to your computer and use it in GitHub Desktop.
Save eXpl0it3r/ab64f517afc135449c7008fbdf639b29 to your computer and use it in GitHub Desktop.
Pausable Clock
#include <SFML/Graphics.hpp>
class PausableClock
{
sf::Clock m_clock;
sf::Time m_elapsed;
bool m_isRunning = false;
float m_skewFactor = 1.f;
public:
void start()
{
m_clock.restart();
m_isRunning = true;
}
void pause()
{
m_elapsed += sf::seconds(m_clock.getElapsedTime().asSeconds() * m_skewFactor);
m_isRunning = false;
}
void reset()
{
m_elapsed = sf::Time::Zero;
}
bool isRunning()
{
return m_isRunning;
}
sf::Time getElapsedTime()
{
if (m_isRunning)
{
m_elapsed += sf::seconds(m_clock.restart().asSeconds() * m_skewFactor);
}
return m_elapsed;
}
void setSkewFactor(float skewFactor)
{
m_skewFactor = skewFactor;
}
};
int main()
{
auto window = sf::RenderWindow{sf::VideoMode{500, 200}, "Test"};
window.setFramerateLimit(60);
auto font = sf::Font{};
if (!font.loadFromFile("times.ttf"))
{
return -1;
}
auto text = sf::Text{"0.0 passed", font, 12u};
text.setStyle(sf::Text::Bold);
auto pausableClock = PausableClock{};
pausableClock.start();
auto skew = 1.f;
while (window.isOpen())
{
for (auto event = sf::Event{}; window.pollEvent(event);)
{
switch (event.type)
{
case sf::Event::Closed:
window.close();
break;
case sf::Event::KeyPressed:
if (event.key.scancode == sf::Keyboard::Scan::Up)
{
skew += 0.1f;
pausableClock.setSkewFactor(skew);
}
else if (event.key.scancode == sf::Keyboard::Scan::Down)
{
skew -= 0.1f;
pausableClock.setSkewFactor(skew);
}
else if (event.key.scancode == sf::Keyboard::Scan::Space)
{
if (pausableClock.isRunning())
{
pausableClock.pause();
}
else
{
pausableClock.start();
}
}
else if (event.key.scancode == sf::Keyboard::Scan::Escape)
{
pausableClock.reset();
}
break;
default:
break;
}
}
text.setString(std::to_string(pausableClock.getElapsedTime().asSeconds()) + " passed\n(Skew: " + std::to_string(skew) + ")");
window.clear();
window.draw(text);
window.display();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment