1

Newbie here, I'm creating a Flappy Bird clone using XNA and up until now I'd encountered no unsolvable problems, but I just don't know how to proceed on the spawning of pipes.

I have a pipe class, and I manage to create an instance of it based on a timer in the main game update function (I know this will create the pipe only once):

elapsedTime = (float)gameTime.ElapsedGameTime.TotalSeconds;

if (elapsedTime == 1.0f)
{
    Pipe pipe = new Pipe();
}

The problem is that I can't call the pipe.Update() function in the main game update, given that "pipe" hasn't been created yet! And, in any case if I'm to spawn several instances of Pipe.cs, how do I refer to their respective Update() functions?

CodeSmile
  • 64,284
  • 20
  • 132
  • 217
Bensas
  • 101
  • 1
  • 9

1 Answers1

1

To create multiple pipes, you could use a list and simple for loops (I added a spawntime factor to make a pipe spawn every 5 seconds to give you an idea of how you could spawn):

List<Pipe> pipes = new List<Pipe>();
int spawnfactor = 5;
int spawns = 0; //or 1, if you want the first spawn to occur at 1 second

protected override void Update()
{
    elapsedTime = (float)gameTime.ElapsedGameTime.TotalSeconds;

    if (elapsedTime == spawnfactor * spawns)
    {
        pipes.Add(New Pipe());
        spawns++; //keep track of how many spawns we've had
    }

    for (int i = 0; i < pipes.Count; i++)
    {
        pipes[i].Update();//update each pipe in the list.
    }
}

protected override void Draw()
{
    for (int i = 0; i < pipes.Count; i++)
    {
        pipes[i].Draw();
    }
}

Let me know if this helps or if anything's unclear.

davidsbro
  • 2,761
  • 4
  • 23
  • 33
  • That's perfect, thanks! I'm having some trouble understanding how those for loops work though, as I've only used loops in python up until now. Would you mind explaining the `(int i = 0; i < pipes.Count; i++)` part a bit further? – Bensas Mar 04 '14 at 02:11
  • Sure! Glad it helped. If it answered your question, feel free to mark it as so. :) Basically, what the loops does is `int i = 0;` declares the variable `i` and sets it to zero, `i < pipes.Count` iterates through the loop WHILE `i` is less than the `pipes.count`, and `i++` means add 1 to `i` each iteration. – davidsbro Mar 04 '14 at 02:13
  • @user3376800 Sure! If you have any other questions, feel free to ask. Also, I meant to show you this link. Hopefully it will explain the loop in more detail http://msdn.microsoft.com/en-us/library/ch45axte.aspx Good Luck! – davidsbro Mar 04 '14 at 02:16