There are many uses for timers in games. Timing a game session, score based on time, countdowns, cooldowns, etc. Creating a timer is pretty simple.
Every tick you add dt to the timer variable. dt is the time since the last tick (see the dt tutorial) so adding dt every tick means timer will equal the total time (in seconds) passed since you started adding. After 1 second the timer variable will equal 1 etc.
Converting seconds into hr/min/sec
To display as hours/minutes/seconds you can convert with the following formulas:
hours = floor(timer / 3600)
minutes = floor(timer / 60 % 60)
seconds = floor(timer % 60)
For a countdown timer, set the variable to the countdown duration. Then subtract dt every tick as long as the timer > 0. I subtract dt by setting the variable to max(0, variable - dt). This ensures that the value won’t go below 0.
When the value reaches 0 you can start your game or do whatever it is you want to do after the countdown. You may need a ‘System: Trigger Once’ condition alongside the ‘System: countdown = 0’ condition so that your event only happens once when the timer ends.
Timing gameplay works in the same way:
Every x seconds
There’s the built-in ‘Every x seconds’ condition that runs every x seconds from the start of the game. But sometimes you want an event to run every x seconds starting when the level starts or when a button is pressed etc.
Same deal as before, subtracting dt from the timer until it reaches 0. This time the timer variable is an instance variable of the turret, as each turret will have it’s own separate timer. When the timer reaches 0, the turret shoots and the timer is reset to the value stored in the turret’s delay variable. Of course you don’t need to create your own timers for everything, sometimes ‘System: Wait x seconds’ or ‘System: Every x seconds’ will do the job just fine.
Another way to time the duration of something is to just store the start time and the end time. The total time taken is then endTime - startTime.