Thursday, 18 November 2021

C++ & SFML // Simple Timer

So I'm currently working my way through making a clone of Space Invaders using SFML and I got to the point where I needed to do something after X amount of seconds. Usually I use FLTK and that would've been simple using it's callback system however SFML is event based and as such doesn't really supply a "timer system" out of the bag like fltk.

Therefore I googled and eventually found pieces of what I was looking for and managed to put this simple demonstration together for those who just want to figure out how to get seconds displayed on the screen. This is what the "tutorial" will give you:

C++ & SFML // Simple Timer displaying seconds passed

The program does 2 things:
1) Display the number of seconds since the program started
2) Every second it chooses a random message (from 4) to display.

Very exciting. Let's begin.

Here is the full code:

Have a look, it's all in main for simplicity. 

There is a clock that is restarted at the beginning of the main loop and assigned to DeltaTime.
SFML have handily provided a way to get the DeltaTime as seconds. All you have to do then is += that to a variable defined outside the loop and you have your seconds since the program started.

For the text, I just made a variable that holds the max time we want to show the text for (maxDelay) and another variable to hold the elapsedTime. Getting the elapsed time is the same as getting the seconds above only when updating which message to display, there is a check to see if the elapsed time has gone above the max delay. If so, it changes the message and resets the elapsed time back to zero.

The concepts here can be used for many other things like displaying a sprite for a given amount of time as well creating more complicated things, like an event queue system that dispatches events based on the elapsed time (much more useful for larger projects than above).

for an example on how this can be put together.

No comments:

Post a Comment