Introduction to Time / Timer functions

5
  • 38 favourites

Index

Attached Files

The following files have been attached to this tutorial:

.capx

Stats

9,723 visits, 20,679 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.

Intro

Although there are some timer tutorials here, we'll explore different things you can do with timers.

The time variable is a built-in variable that begins whenever the game starts. With this variable, you can

1. take the time of how long the game is running. In some games, players get points when they are able to survive or continue playing as long as they can

2. save the current time into a global variable for later purpose, for example to do something for x seconds. One example is the hyperspace speed time I used in one of my other tutorials. Another idea would be to use the variable for countdown purposes.

Setup

Create a new project, leave window/layout size as they are.

Insert a text object and give it a name "Timer_txt"

In the Event sheet, we'll tell Construct 2 to show us the time.

Condition: System -> On Every tick

Action: Timer_txt -> Set text to time

Run the game by pressing F5.

Note: if you're not seeing anything, check if your text object's length is not too narrow.

You'll see a floating number showing the seconds and the milliseconds. No minutes, nor hours, etc..

Change the time term to (int(time)) and the text object will show the seconds.

Change the term again to zeropad(int(time),2) and now we'll see leading zeros due to the zeropad function, which is set at 2, which means to fill with leading zeros, until the number is composed of two digits.

To display minutes and hours, we need some math, because after 59 seconds, time will continue with 60, 61, etc..

We'd like to see something like 1:30 or even 01:30 (with leading zeros, of course).

Here, the modulo (%) operand will help us. In a mathematical term, it will return the rest of a division calculation. Examples:

5%2 = 1 (5 divided by 2 is 2, resting 1)

10%6 = 4 (10 divided by 6 is 1, resting 4)

For calculating with time we need to modulo 60:

5%60 = 5 (5 divided by 60 is 0 minutes, resting 5 seconds)

59%60 = 59

60%60=0 (60 divided by 60 is 1 minute, resting 0 seconds)

61%60=1 (1 minute, 1 second)

and so on..

formula for seconds

time % 60

formula for minutes

time/60 % 60

For the text object, we'll set the term

zeropad(int(time/60% 60), 2) & ":" & zeropad(int(time%60), 2)

Note: in other tutorials or forums, some use floor instead of int. You can use any of these

  • 0 Comments

  • Order by
Want to leave a comment? Login or Register an account!