基于SFML库实现程序运行时长实时显示的技术咨询
Hey there! Let's break down your current code and get that total elapsed seconds counter working properly.
First: Why Your Current Code Isn't Showing Total Time
Your existing code uses clock.restart() inside the main loop, and that's the key issue here. Let's clarify what these SFML clock functions do:
- When you create a
sf::Clock, it starts counting time immediately from that moment. clock.restart()resets the clock's start time to the current moment, and returns the time that passed since the last restart (or the clock's creation, if it's the first call).
So in your loop, every iteration you're resetting the clock—meaning you're only getting the time between one frame and the next (called "delta time"), not the total time since the program started. That's great for things like moving sprites smoothly (since you multiply movement speed by delta time), but not for tracking total elapsed seconds.
The Correct Approach: Track Total Elapsed Time
To show the total seconds since launch, you need to use sf::Clock::getElapsedTime() instead. This function returns the time that's passed since the clock was created, without resetting the clock.
Here's how to implement this in your game, step by step:
1. Set Up Your Text Object (For Displaying Time)
First, you need an sf::Text object to render the time on screen. Don't forget to load a font—SFML can't display text without one:
// Put this before your main loop (after creating the window) sf::Font font; // Replace "arial.ttf" with the path to a font file on your system if (!font.loadFromFile("arial.ttf")) { // Handle font loading failure (e.g., print an error and exit) std::cerr << "Failed to load font!" << std::endl; return 1; } sf::Text timerText; timerText.setFont(font); timerText.setCharacterSize(30); // Adjust size as needed timerText.setFillColor(sf::Color::White); timerText.setPosition(20, 20); // Place it in the top-left corner
2. Track Total Time With a Clock
Create your clock outside the main loop (so it only starts once, when the program launches):
sf::Clock totalRuntimeClock; // Starts counting as soon as it's created
3. Update and Draw the Timer in the Loop
Inside your main window loop, get the total elapsed time, update the text, and draw it:
while (window.isOpen()) { sf::Event event; while (window.pollEvent(event)) { if (event.type == sf::Event::Closed) window.close(); } // Get total elapsed time since program start sf::Time totalTime = totalRuntimeClock.getElapsedTime(); // Convert to seconds (as a float) and format the string float totalSeconds = totalTime.asSeconds(); // Format to show 2 decimal places for readability std::string timerString = "Elapsed Time: " + std::to_string(totalSeconds).substr(0, 5) + "s"; timerText.setString(timerString); // Clear the window, draw your timer (and other game elements), then display window.clear(sf::Color::Black); window.draw(timerText); // Draw your game sprites/UI here window.display(); }
Quick Recap of Clock Functions
- Use
clock.getElapsedTime()when you need total time since the clock started (like your timer). - Use
clock.restart()when you need time since the last frame (delta time) for game logic (e.g., moving objects, updating animations).
That should give you a working on-screen counter that shows the total seconds your program has been running, until the window closes.
内容的提问来源于stack exchange,提问作者Basma Ashour

