OpenGL迷宫游戏中SFML Clock无法正确重启的问题求助
Hey there! Let's work through why your SFML Clock isn't restarting properly for your maze game timer.
What's Likely Going Wrong
Looking at your code snippet, the core issue probably boils down to one of these two things:
- You're not resetting
mazeOneIterationafter the maze is completed: Your logic only restarts the clock whenmazeOneIteration == 1, then increments it to 2. If you never setmazeOneIterationback to 1 when the player finishes the maze (or wants to retry), the restart condition will never trigger again, and the clock will keep counting from the previous run's time. - Timing of the restart vs. draw call: You're drawing the maze before checking the restart condition, which might mean the first frame of the maze displays an unstarted clock value.
Fixes to Try
1. Reset the Iteration Variable When the Maze Ends
When the player completes the maze (or you need to reset it for a retry), make sure to set mazeOneIteration back to 1. This ensures the clock restart logic will fire again on the next run:
// Example: Add this where you handle the player finishing the maze if (playerHasReachedMazeExit()) { // Record the final time if needed float finalTime = mazeOneClock.getElapsedTime().asSeconds(); // Reset the iteration marker for next run mazeOneIteration = 1; // Other logic: switch levels, show completion screen, etc. }
2. Adjust the Restart Logic Order
Move the clock restart check before drawing the maze, so the timer starts exactly when the maze is first rendered:
// First check if we need to restart the clock if(mazeOneIteration == 1){ mazeOneClock.restart(); // Start timing before drawing mazeOneIteration++; } // Then draw the maze maze.draw(); // Generate and draw your UI text as before char timeStr1[100]; char levelStr[100]; sprintf(levelStr, "Level: %d", levelNum); sprintf(timeStr1, "Time: %.2fs", mazeOneClock.getElapsedTime().asSeconds()); // Don't forget to draw these text strings to your SFML window!
3. Double-Check the Clock's Scope
Make sure mazeOneClock is a persistent variable (like a class member or a global variable, not a local variable inside your draw/update function). If it's recreated every frame, it'll never hold a consistent timer value.
4. Optional: Use a Boolean for Clearer Logic
Instead of an iteration counter, a boolean flag makes the timer logic easier to read and maintain:
// Initialize this once (e.g., in your class constructor or global setup) bool isMazeOneActive = false; // When starting the maze: if (!isMazeOneActive) { mazeOneClock.restart(); isMazeOneActive = true; } // When finishing the maze: if (playerHasReachedMazeExit()) { float finalTime = mazeOneClock.getElapsedTime().asSeconds(); isMazeOneActive = false; }
Give these adjustments a shot—they should get your timer restarting correctly for each maze run.
内容的提问来源于stack exchange,提问作者Zack Sloan

