Delay a xna game with timers
13,250
float WaitTimeToShowCard = 0;
public void Update(GameTime gametime)
{
if (HasToShowCard ())
{
WaitTimeToShowCard = 1;
}
if (WaitTimeToShowCard >0)
{
WaitTimeToShowCard -= (float) gametime.Elapsed.TotalSeconds;
if (WaitTimeToShowCard <=0)
{
WaitTimeToShowCard = 0;
ShowCard();
}
}
}
or
public class Timer
{
public Action Trigger;
public float Interval;
float Elapsed;
Timer() {}
public void Update(float Seconds)
{
Elapsed+= Seconds;
if (Elapsed>= Interval)
{
Trigger.Invoke();
Destroy();
}
}
public void Destroy()
{
TimerManager.Remove(this);
}
public static void Create(float Interval, Action Trigger)
{
Timer Timer = new Timer() { Interval = Interval, Trigger = Trigger }
TimerManager.Add(this);
}
}
public class TimerManager : GameComponent
{
List<Timer> ToRemove = new List<Timer>();
List<Timer> Timers = new List<Timer>();
public static TimerManager Instance;
public static void Add(Timer Timer) { Instance.Timers.Add( Timer ); }
public static void Remove(Timer Timer) { Instance.ToRemove.Add(Timer); }
public void Update(GameTime gametime)
{
foreach (Timer timer in ToRemove) Timers.Remove(timer);
ToRemove.Clear();
foreach (Timer timer in Timers) timer.Update( (float) gametime.Elapsed.Totalseconds);
}
}
public class Game
{
public void Initialize() { Components.Add(new TimerManager(this);}
public Update()
{
if (HasToShowCard(out card))
{
Timer.Create(1, () => card.Show());
}
}
}
Related videos on Youtube
Author by
Tom
Updated on June 09, 2022Comments
-
Tom almost 2 years
I'm making a blackjack game where a card needs to be shown a second after the last card. I've googled it and saw Thread.Sleep - but people said timers would be better for that. How can I do this with timers? Thanks!
-
Joey over 12 yearsYou shouldn't use either (especially don't use
Thread.Sleep
). Accumulate thegameTime.ElapsedGameTime
whenGame.Update
is called. -
MattDavey over 12 years@Andrew Russel +1 Thread.Sleep should be avoided in 99.9% of cases where you might be tempted to use it!
-
-
MattDavey over 12 yearsIs System.Timers.Timer available in the compact framework? Might be worth letting the OP know he's sacrificing Xbox and phone support by using it..
-
NBcode over 12 yearsHmm.. I don't know if it is.. but I can't comment on his original question to notify him. (If you see this, and want Xbox or phone support, use the suggestion by Andrew Russel
-
TJHeuvel over 12 yearsEventhough the OP asked for timers, it really isnt the best solution in game development.