Simple DELTA-TIMER

Share your advanced PureBasic knowledge/code with the community.
neumanix
User
User
Posts: 11
Joined: Thu Aug 13, 2009 3:13 pm
Location: Finland

Simple DELTA-TIMER

Post by neumanix »

I'm just starting out and am quite proud of myself for figuring out what seems to be a working delta-timer.
Please let me if know I did something stupid :lol:

I thought it might be helpful for beginners like myself.

:!: Make sure the debugger is ON to see the FPS

Also, to simulate running on a slow computer, increase the delay value to 50 or more

Code: Select all

; DELTA-TIMER
; by neumanix 2011

; You can test with/without VSYNC and with/without Delay(1)

InitSprite()

win_id=OpenWindow(1,100,100,800,32,"FPS test",#PB_Window_ScreenCentered | #PB_Window_BorderLess)

; comment out one of the two lines below
OpenWindowedScreen(win_id,0,0,800,32,0,0,0,#PB_Screen_NoSynchronization) ; no vsync
;OpenWindowedScreen(win_id,0,0,800,600,0,0,0) ; vsync

StartDrawing(ScreenOutput())
  Box(0,0,32,32,RGB(255,255,255)) ; draw something to grab
StopDrawing()

sprite=CreateSprite(1,32,32)
GrabSprite(1,0,0,32,32)

angle.f=0 ; float variable for the Sin() calculation
delta.f=0 ; delta speed float variable
speed=250 ; The speed you want for the sprite (pixels per sekund)

starttime=ElapsedMilliseconds() ; get the current time

Repeat 
  event=WindowEvent() ; has to be here although not used in this example
  
  ClearScreen(0)
  
  x=Sin((angle/180*#PI))*400-16 ; -16 = half the sprite width so it centers correctly
  
  DisplaySprite(1,400+x,0)

  angle+delta ; add the delta to anything that moves, in this case the angle value
  
  fps+1 ; counts frames elapsed
  
  If time>1000; has one second passed?  
    Debug "FPS: "+Str(fps-1)
    
    delta=speed/fps ; calculate delta 
    
    fps=0 ; reset the frame counter
    
    starttime=ElapsedMilliseconds() ; reset the starttime   
  EndIf
  
  Delay(1) ; comment out this line for full speed and max CPU usage
  FlipBuffers()
  
  time=ElapsedMilliseconds()-starttime
Until GetAsyncKeyState_(#VK_ESCAPE)

CloseScreen()
CloseWindow(1)
End