| hertz - how many times per second the timer should tick; 60 is a common choice |
|
Creates a timer that ticks a fixed number of times per second. A timer on its own does nothing visible - it is a metronome you then wait on with WaitTimer. Create one at 60 hertz, call WaitTimer at the top of your main loop, and the loop runs at 60 iterations a second on every machine instead of as fast as the hardware allows. That is the point: without pacing, a game written on a slow machine sprints on a fast one. A timer gives you a fixed update rate to build your movement and animation speeds against. Store the handle it returns in a variable, since you need it for every WaitTimer call and to free it later. It is common to keep the handle in a Global so functions can reach it. The tick period is worked out in whole milliseconds, so rates that do not divide neatly into 1000 are rounded - 60 hertz becomes a 16 millisecond period, which is a shade fast. If you need exact timing rather than approximate pacing, drive your loop from MilliSecs deltas instead. A rate of 0 or less is treated as 1 millisecond. Release the timer with FreeTimer when you are done with it. See also: WaitTimer, FreeTimer, MilliSecs, Delay, Flip. |
; CreateTimer Example
; -------------------
Graphics 640,480,0,2
SetBuffer BackBuffer()
; CreateTimer(hertz) makes a timer that ticks at a fixed rate. Waiting
; on it with WaitTimer locks the main loop to that rate, so the game
; runs at the same speed on fast and slow computers.
hertz=60
timer=CreateTimer(hertz)
frames=0
fps=0
fps_time=MilliSecs()
While Not KeyDown(1)
Cls
; 1/2/3 rebuild the timer at a new rate (freeing the old one)
new_hertz=0
If KeyHit(2) Then new_hertz=15
If KeyHit(3) Then new_hertz=60
If KeyHit(4) Then new_hertz=120
If new_hertz>0 Then
FreeTimer timer
hertz=new_hertz
timer=CreateTimer(hertz)
EndIf
; One step per loop: the timer's rate IS the square's speed
x=(x+4) Mod 640
Rect x,220,40,40,True
; Count real frames per second to show the timer is in charge
frames=frames+1
If MilliSecs()-fps_time>=1000 Then
fps=frames
frames=0
fps_time=MilliSecs()
EndIf
Text 0,0,"1: 15 Hz 2: 60 Hz 3: 120 Hz Esc: exit"
Text 0,20,"timer=CreateTimer("+hertz+") measured "+fps+" fps"
; Flip False: don't also wait for the monitor - the timer sets the pace
Flip False
; Wait here until the timer's next tick
WaitTimer(timer)
Wend
End