Tuesday, September 3, 2013

Timer Component (Updated)

What I did today:


Another sick day (well, more like, never got over what I had a two weeks ago).

So instead, let's talk about useful components.

Useful component #1:

I noticed I was putting timers into several different components, duplicating a lot of code (and implementing it inconsistently, with "Frequency" sometimes meaning "events per second" and other times meaning "time between events").

Why not make a timer its own component?

You basically need these things:
  • Frequency (float) - events generated per second
  • Prime (bool) - if true, the first event happens immediately
  • TimerTick (event handler / delegate) - list of objects listening to the timer
Then internally, you need:
  • EventCount (float) - fractional timer counter

EventCount = Prime ? 1.0f : 0.0f;

Add the event callback:

TimerTick += <event handler function>;

Then your update loop just looks like:

EventCount += Frequency * delta_time;
while (EventCount >= 1.0f)
    EventCount -= 1.0f;

Basically, you figure out how many events were to be spawned that frame, spawn that many, and keep the fractional remainder for the next frame.  This works to trigger from hundreds of times per frame, to once every hundreds of frames. It will also trigger just once if you primed the timer and set frequency to zero.

Nitpicker extraordinaire Angelo Pesce suggests that the Prime value should be a float used to initialize EventCount to allow phase offsets in timers of the same frequency... sure, why not, sounds good to me!  :)

No comments:

Post a Comment