Having trouble declaring a new object

Hello guys. I am stuck on my project again. Sorry to disturb you all. I am trying to create a simple game where a particular colored box goes to its location. For example, a red box should cross the red line and a green box should cross the green line. I am having trouble with creating a new box after the previous box crosses the line or goes after the screen after crossing the line. I can either create one box or multiple boxes at the same time.

I am planning to have 100 boxes. Each of them appearing one by one after the previous one crosses the line.

Your advice and help will be much appreciated.
Thanks in advance.
Farhan Hasan

int BoxNumber = 0; 
Box[] boxes = new Box[2]; 
void setup()
{
  size(800, 500); 


  boxes[BoxNumber] = new Box();
  if (boxes[BoxNumber].x < 0 || boxes[BoxNumber].x > width)
  {

    BoxNumber++;
    boxes[BoxNumber].x = random(70, width - 70); //A new box should be created between the lines when the previous box is out of the screen 
    boxes[BoxNumber] = new Box();
  }
}

void draw()
{
  background(125); 
  //LINES 

  //GREEN LINE 
  noStroke(); 
  fill(#2DCE1F); 
  rect(50, 0, 10, height * 2); 

  //RED LINE
  noStroke(); 
  fill(#CE1F1F); 
  rect(width - 50, 0, 10, height *2); 






  boxes[BoxNumber].show(); 
  boxes[BoxNumber].comingTowardsYou(); 
  //boxes[BoxNumber].reset(); 




  // println(boxes.length);
}


//CONTROLLING THE BOXES
void keyPressed()
{

  if (key == 'a' || key == 'A')
  {

    boxes[BoxNumber].moveLeft();
  } else if (key == 'd' || key == 'D')
  {
    boxes[BoxNumber].moveRight();
  }
}
class Box
{
  float x = random(70, width - 70);  
  float y = height/2; 
  float len = 40;  
  float sizeIncrease = random(0.01, 2); 

  void show()
  {
    rectMode(CENTER); 
    noStroke(); 
    fill(#2DCE1F); 
    rect(x, y, len, len); 

    //println(sizeIncrease);
  }

  void comingTowardsYou()
  {
    len = len + sizeIncrease;
  }

  void moveLeft()
  {


    sizeIncrease = 0; 
    x = x - 20;
  }

  void moveRight()
  {


    sizeIncrease = 0; 
    x = x + 20;
  }

  void reset()
  {
    if (x < 0 || x > width)
    {
      x = width/2;
    }
  }
}

You need to swap the last two lines because you are attempting to use the box before creating it

1 Like