Using timers

Description

Timers are likely to play a key part in your games, for example, triggering events, countdowns and much more. In this example a sprite has its colour changed after a certain amount of time has passed.

Overview

The process involved is as follows:

Store the current time

AppGameKit Studio provides a function that tells you how many seconds have passed since the application was started. This command is called GetSeconds and it returns an integer. When more accuracy is required it's recommended to use the command Timer ( ) that returns a floating point number. This number contains the seconds and fractions of a second that have passed since the application was started (accurate to milliseconds). For the purposes of our example we only require the number of seconds passed:

initialTime = GetSeconds ( )

With the seconds stored within the variable initialTime we can proceed to the next step.

Main loop

Once four seconds have passed our intention is to change the colour of our previously created sprite. This is easily handled by calling GetSeconds again and comparing it to the "initialTime" variable that was stored at the beginning of the application. If GetSeconds is 4 seconds greater than initialTime we can proceed to change the colour of our sprite. Here's the code for dealing with this:

do
    if ( GetSeconds ( ) > initialTime + 4 )
        SetSpriteColor ( sprite, 0, 255, 0, 255 )
    endif

sync ( ) loop

Full code listing

Everything is now in place. Here's the final code for our program:

SetVirtualResolution ( 320, 480 )

CreateSprite ( LoadImage ( "background6.jpg" ) )
image = LoadImage ( "button.png" ) sprite = CreateSprite ( image ) SetSpritePosition ( sprite, 100, 170 )
initialTime = GetSeconds ( )
SetPrintColor ( 0, 255, 0 )
do Print ( "After 4 seconds the button" ) Print ( "will turn green" )
if ( GetSeconds ( ) > initialTime + 4 ) SetSpriteColor ( sprite, 0, 255, 0, 255 ) endif
Sync ( ) loop

Conclusion

For more details on timers please view the Reference Guide.