在数组中迭代XNA游戏时间延迟计时器

时间:2014-06-08 14:32:24

标签: c# arrays loops for-loop xna

我正在尝试遍历一个子弹阵列,以便设置每个子弹的位置,延迟为0.3秒。

FireTimer += (float)gameTime.ElapsedGameTime.TotalSeconds;

            if (kbState.IsKeyDown(Keys.Space) && FireTimer > FireRate)
            {
                for (int i = 0; i < bullets.Count(); i++)
                {
                    if (bullets[i].IsAlive == false)
                    {
                        bullets[i].IsAlive = true;
                        bullets[i].position = position;
                        FireTimer = 0f;
                    }
                }

            }

我的FireTimer被赋值为0.0f,FireRate被赋值为0.3f。

当我调用此方法时,所有项目符号都被绘制并给出相同的位置。任何人都可以告诉我需要做些什么来让他们以0.3秒的间隔定位在这个位置?

1 个答案:

答案 0 :(得分:0)

当按键关闭时,您正在检查firetimer,然后迭代整个阵列并触发每个子弹。您将需要一个变量来存储剪辑中的当前索引,然后在每次触发子弹时将其递增。

int clipIndex = 0;

...


FireTimer += (float)gameTime.ElapsedGameTime.TotalSeconds;

if (kbState.IsKeyDown(Keys.Space) && clipIndex < bullets.Count() FireTimer > FireRate)
{
    if (bullets[clipIndex].IsAlive == false)
    {
        bullets[i].IsAlive = true;
        bullets[i].position = position;
        FireTimer = 0f;
    }
    clipIndex++;
 }

然后可以通过将索引更改回0来重新加载;另一件需要注意的事情,如果子弹的旗帜IsAlive是真的,那么这个错过了单帧的火力。如果你想找到下一个活着的子弹你可以做一会儿声明:

while (bullets[clipIndex].IsAlive && clipIndex < bullets.Count())
    clipIndex++;

if (clipIndex < bullets.Count())
    ...

if语句会发生变化,因为你知道clipIndex将是一个没有活着的项目符号的索引,但你确实想确保它有一颗子弹。

相关问题