Skip to main content
GameDev.net gamedev.net
🔒 Locked

How to make a timer using XNA?

Started by Gamesmaster3 Nov 24, 2007 at 10:17 PM 3 replies 11.5k views
Original Post
Gamesmaster3
Gamesmaster3
Does anyone know how to make a timer using XNA? If you know where I can find the information that would be just as good.I don't mind figuring it out myself but I've been looking for a tutorial all day and keep running up on one dead end after another. Basically what I'm doing is making a slide show program.Everything is working but the images are coming by much to fast.I've tried getting the coputer to count to a large number hoping that the time it takes the computer to count to it would be a long enough pause but to no avail.
NickGravelyn
NickGravelyn
I don't have anything like a Wait command (those are generally bad in games), but I do have a GameComponent that is a Timer:

	public class TimerComponent : GameComponent	{		TimeSpan interval = new TimeSpan(0, 0, 1);		TimeSpan lastTick = new TimeSpan();		public event EventHandler Tick;		public TimeSpan Interval		{			get { return interval; }			set { interval = value; }		}		public TimerComponent(Game game)			: base(game)		{		}		public override void Update(GameTime gameTime)		{			if (gameTime.TotalGameTime - lastTick >= interval)			{				if (Tick != null)					Tick(this, null);				lastTick = gameTime.TotalGameTime;			}		}	}


Then you just tell it how long you want it to go to using the Interval property and give it an event handler for the Tick event and it will send out the events as necessary. Then you just swap your pictures out in that event handler and you'll be all set.

Hope that helps.
Gamesmaster3
Gamesmaster3
Actually I think it will help alot.At the very least it now gives me a starting place so I can figure it out.So is TimerComponent something that comes along with XNA or is it like a method you've made yourself?

Thanks for the help and the quick replay Nick
NickGravelyn
NickGravelyn
It's just something I wrote. I needed a way to spawn an enemy every so often. So I made this class up to do the timing for me.
Andorien
Andorien
The .Net Framework provides everything you need, which you have access to by virtue of using XNA.

What you're looking for is System.Timers.Timer.

Use it like this:
void PictureSwap(object o, System.Timers.ElaspedEventArgs e){    ... // Relevant picture code here}System.Timers.Timer t = new System.Timers.Timer(1000); // This creates a new timer that will fire every second (1000 milliseconds)t.Elapsed += new System.Timers.ElapsedEventHandler(PictureSwap); // Register the function with the timert.Enabled = true; // Start the timer!


The timer class with call your function every second (or however long you tell it to). Be aware that the function is fired on a new thread, so you can have other stuff going on too.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.