Delayed xna game with timers

I am making a blackjack game where the card should be shown a second after the last card. I looked for it and saw Thread.Sleep - but people said that timers would be better for this. How can I do this with timers? Thanks!

+6
source share
2 answers
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()); } } } 
+10
source
 using System.Timers; . . . public class Game1 : Microsoft.Xna.Framework.Game { GraphicsDeviceManager graphics; SpriteBatch spriteBatch; Timer t = new Timer(1000); //The number is the interval in miliseconds public Game1() { graphics = new GraphicsDeviceManager(this); Content.RootDirectory = "Content"; t.Elapsed += new ElapsedEventHandler(t_Elapsed); t.Enabled = true; } void t_Elapsed(object sender, ElapsedEventArgs e) { //code } . . . } 

I copied some bits of code to show the positioning of the added code ... Also, after entering "t.Elapsed + =", press the TAB key twice to create an event handler. If you want to stop the timer, set the Enabled property to false. ('t' is the name of a bad variable)

0
source

Source: https://habr.com/ru/post/895641/


All Articles