Compute event.lastFrameTime

1 reply [Last post]
DGuy's picture
DGuy
User offline. Last seen 24 weeks 6 days ago. Offline
Joined: 7 Jul 2009

This piece of code will compute the last-frame-time (very useful when doing time-based animation) and make it available to all enterFrame event handlers that follow. You'll want to place/require() this code very early (if not first) in your program:

1
2
3
4
5
6
7
8
9
local function onEnterFrame_computeLastFrameTime()
  local prev_time = nil
  return function( event )
    prev_time = prev_time or event.time
    event.lastFrameTime = (event.time - prev_time) / 1000 -- '/ 1000' converts from msecs to secs
    prev_time = event.time
  end
end
Runtime:addEventListener( "enterFrame", onEnterFrame_computeLastFrameTime() )

David

Replies

afyzendo
User offline. Last seen 1 year 17 weeks ago. Offline
Joined: 9 Feb 2010

I like how you keep prev_time local by returning a function.
That's a useful pattern!

Thanks, Arjan

Viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.