敌人之间的产生延迟

时间:2012-05-07 11:04:41

标签: c# xna delay spawning

我正在XNA的一个塔防游戏中工作,我有一个名为Tank的类,它会创建一个敌人,它遵循通过A *找到的地图周围的路线。 现在,我可以创建多个Tank实例,但它们都会同时生成。这意味着它们与路线完全相同,使其看起来只有一个敌人。

以下是我加载新wave的代码:

if (spawn == true)
{
    maxTanks += 2;
    killsInWave += 2;

    tanks = new Tank[maxTanks];
    for (int i = 0; i < maxTanks; i++)
    {
        tanks[i] = new Tank();
        tanks[i].Initialize(map);
        tanks[i].LoadContent(Content);                                  
    }
    waveNum += 1;
    spawn = false;
}

有人能给我一些帮助,让每个敌人在它和最后一个之间产生延迟吗?

3 个答案:

答案 0 :(得分:1)

您需要基于时间的生成创建率,类似于此...

   SpawnUnitsCount = n;
   Units_Per_Second = 5; // 5 Per second

   void Update(float ElapsedSeconds)  // (float) gametime.ElapsedTime.TotalSeconds
   {      
    if (SpawnUnitCount>0)
    {
      CreationRate += Units_per_second * ElapsedSeconds;
      while ( CreationRate >= 1 )
      {
         CreationRate--;
         MakeNewUnit(); 
         SpawnUnitsCount --;
         if (SpawnUnitCount == 0)
         {
            CreationRate = 0; // The wave is finished
         }
      }
    }

答案 1 :(得分:0)

我会这样做:

//need to be defined in your loop
int nextTankToCreate(0);
int iterationCount(0);
int CreateTime(500); //create every 500 iteration

iterationCount++;
if (spawn == true && iterationCount >= createTime)
        {
            iterationCount = 0;
            maxTanks += 2;
            killsInWave += 2;

            tanks = new Tank[maxTanks];
            tanks[nextTankToCreate] = new Tank();
            tanks[nextTankToCreate].Initialize(map);
            tanks[nextTankToCreate].LoadContent(Content);                                  
            nextTankToCreate++;

            if (nextTankToCreate == maxTanks)
            {
                nextTankToCreate = 0;
                waveNum += 1;
                spawn = false;
            }
        }

答案 2 :(得分:0)

不确定XNA是否具体,但如果您需要执行一些间隔的重复操作,您可以使用类似的东西:

        Action addTank = null;
        int interval = 1000; // 1000 milliseconds
        int requiredNumberOfTanks = 10;
        int tanksCreated = 0;

        var timer = new Timer(o => addTank());
        addTank = () =>
                         {
                             CreateTankMethod();  // your method to create tank
                             tanksCreated = tanksCreated + 1;
                             if (tanksCreated < requiredNumberOfTanks)
                                 timer.Change(interval, 0);
                         };
        timer.Change(interval, 0);

此代码将以最有效的方式利用线程。它比Thread.Sleep()

好得多

您可能还希望让坦克之间的间隔更随机。