c# – 使用计时器延迟xna游戏

前端之家收集整理的这篇文章主要介绍了c# – 使用计时器延迟xna游戏前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在制作一个二十一点游戏,其中一张卡需要在最后一张卡后显示一秒钟.
我用Google搜索并看到了Thread.Sleep – 但人们说定时器会更好.
我如何用计时器做到这一点?
谢谢!

解决方法

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();
         } 
    }
}

要么

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());
          }
     }
}
原文链接:https://www.f2er.com/csharp/244209.html

猜你在找的C#相关文章