Lesson 9: Making a Game; Timing


A super-important and sort of advanced concept is timing. You want your game to run at a constant rate for all players, no matter how fast their system is. A good "frame rate" (how many updates to do per second) is 20.
The Anachronox engine is happy with that update rate, and you can pretty much guarantee you can update that fast, unless you are doing something really awful.

This simple demo shows a timer that counts seconds and frames. No biggie, but you need to have this concept down to make games that everyone can play.

/*#############################################################################
DEFINES
#############################################################################*/

#define $Lesson9 "2"
#define $TimerTest "1"
#define $Before "2"
#define $During "3"
#define $After "4"

/*-------------------------------------------------------
CONSTANTS
-------------------------------------------------------*/
#define %MSPERFRAME "50" //50 milliseconds * 20 = 1 sec
#define %FRAMESPERSECOND "20"

/*#############################################################################
CODE
#############################################################################*/
#window $Lesson9:$TimerTest
startswitch $Lesson9:$Before
thinkswitch $Lesson9:$During
finishswitch $Lesson9:$After

width 256
height 256
title "Timer Test"
body "Seconds: %d Frames: %d", secCounter, frameCounter

/*=======================================================
Before
Initialize stuff!
=======================================================*/
#switch $Lesson9:$Before
lastMS = func_GameTime
currentMS = lastMS
frameCounter = 0 //unnecessary, but establishes
secCounter = 0 //these vars to coders looking
return //at the program

/*=======================================================
During
Actively update appropriate variables
=======================================================*/
#switch $Lesson9:$During
set currentMS = func_GameTime //get starting time, start to count
set delta = currentMS - lastMS
if (delta < %MSPERFRAME) return //do nothing unless frame starts

set lastMS = currentMS

frameCounter = frameCounter + 1
if (frameCounter == %FRAMESPERSECOND)
{
frameCounter = 0
secCounter = secCounter + 1
}
return

/*=======================================================
After
Leave the place like we found it
=======================================================*/
#switch $Lesson9:$After
unset frameCounter
unset secCounter
unset delta
unset lastMS
unset currentMS
return

Invoke 2:1