XNA Short: Performing an action over time

When developing games, you often want to perform an action over a certain amount of times. Common examples are updating the position of something each second, or shooting a bullet each 5 seconds. This can be hard to achieve as the primary unit of time in games are frames, not seconds, not events.

I’ve written a small class to handle this sort of thing and thought it would be cool to share. The class consists of two parts, the constructor and the Update method which should be called in your Update loop.  The class exposes some powerful functionality that you can easily extend upon. Here’s what it has to offer.

  • The class allows you to specify a time after which an action needs to be performed. The Update method returns true when this time has been met. Alternatively, you can specify an Action delegate which will be executed at that point.
  • You can optionally tell the class that the action should loop over time (e.g: shooting a bullet each 5  seconds)

Here are some examples of implementations:

Using the boolean return type to check when the specified time has been method

// in the Constructor

TimeAction t = new TimeAction(TimeSpan.FromSeconds(2), true); //new TimeAction, every 2 seconds in an infinite loop

// (...)

// in the Update region

if (t.Update(gt))
 this.Position.Y += 100;

Using the Action delegate, the same as the one above but Lambda guys preffer it this way:

// in the Constructor

TimeAction t = new TimeAction(TimeSpan.FromSeconds(5), false); //new TimeAction, one time after 5 seconds

// (...)

// in the Update region

t.Update(gt, () => { this.Position.X += 50; });

You can view the complete sourcecode of this class over at Pastebin. Feel free to improve it and let me know in the comments!


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s