Timers

6

Attached Files

The following files have been attached to this tutorial:

.capx

Stats

23,779 visits, 38,119 views

Tools

License

This tutorial is licensed under CC BY 4.0. Please refer to the license text if you wish to reuse, share or remix the content contained within this tutorial.

Published on 25 Jan, 2013. Last updated 19 Feb, 2019

Download capx.

Simple Timer

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)

Countdown Timer

.

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.

Gameplay Timer

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.

Timing duration

.

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.

Download capx.

.CAPX
  • 1 Comments

  • Order by
Want to leave a comment? Login or Register an account!
  • So every tick I add dt to timer (text object) it shows the timer as its counting up but shows it to the 100 thousandths mark. I'm trying to get that shortened to the tenth mark instead. Any help would be great.