Search code examples
c++sfml

SFML seconds counter


I'm making a game using SFML Library, I wanna implement a function showing the seconds on the screen since the running of the program, and it will get increasing until the window is closed. I tried this:

sf::Clock clock;
while (window.isOpen())
{
    sf::Time elapsed = clock.restart();
    updateGame(elapsed);

}

But I have no idea how it's work or even if it's the right function. Here is my code so far https://github.com/basmaashouur/GamesLib/blob/master/cards/main.cpp


Solution

  • There are multiple ways to get the number of seconds.

    First of all, you can use an exclusive sf::Clock for this that's never reset:

    sf::Clock clock;
    
    const unsigned int seconds = static_cast<unsigned int>(clock.getElapsedTime().asSeconds());
    

    As an alternative, you can use an sf::Time to accumulate the time between frames (e.g. inside your updateGame() function):

    sf::Clock clock;
    sf::Time time;
    
    time += clock.restart();
    
    const unsigned int seconds = static_cast<unsigned int>(time.asSeconds());