Frame limiter (a.k.a. Delta-time) example

Show Index

Try out this example code to see the difference between using a simple timer versus using Delta-timing.  You will notice that the movement of the red square across the screen is much smoother using Delta-timing.

;Timing comparison example
Graphics 800, 600
box = CreateImage(64, 64)
SetBuffer ImageBuffer(box)
Color 255, 0, 0
Rect 0, 0, 64, 64
SetBuffer BackBuffer()

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;First example; using a simple timer to set the framerate
;Notice that the FPS is set to 47 to intentionally not be
;compatible with the current screen refresh rate

xpos = 0

timer = CreateTimer(47)

While Not KeyHit(1)
	;Move the box
	xpos = xpos + 4
	DrawImage box, xpos, 300
	If xpos > 800 Then xpos = 0

	Text 0, 0, "Without Delta-timing..."
	Text 0, 20, "Press Esc to continue."
	
	;Flip the screen
	WaitTimer(timer)
	Flip
	Cls
Wend

FreeTimer timer

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;Second example; using Delta-timing to achieve a smoother movement

Type FrameRate
  Field TargetFPS#
  Field SpeedFactor#
  Field CurrentTicks
  Field FrameDelay
End Type

Global FL.FrameRate = New FrameRate
FL\TargetFPS# = 47
FL\FrameDelay = MilliSecs()

xpos = 0

While Not KeyHit(1)
	;Set Speed Factor
	FL\CurrentTicks = MilliSecs()
	FL\SpeedFactor# = (FL\CurrentTicks - FL\FrameDelay) / (1000.0 / FL\TargetFPS#)
	If FL\SpeedFactor# <= 0 Then FL\SpeedFactor# = 0.00000000001
	FL\FrameDelay = FL\CurrentTicks
	
	;Move the box
	xpos = xpos + 4 * FL\SpeedFactor#
	DrawImage box, xpos, 300
	If xpos > 800 Then xpos = 0
	
	Text 0, 0, "With Delta-timing..."
	Text 0, 20, "Press Esc to end."
	
	;Flip the screen
	Flip
	Cls
Wend
End

 

If you've reached this page and there's no index on the left, Click here to show the Index Page