Problem with bouncing ball program with mousePress

Im trying to create a program where balls bounce around the screen and when they hit each other they collide and when mousePressed create another ball, but nothing is showing on my sketch window.

Ball[] balls = new Ball[5];

void setup() {
  size(600, 500);
  for (int i = 0; i < balls.length; i++) {
    balls = (Ball[]) append(balls, new Ball(random(0,width),random(0,height)));
  }
}
void mousePressed(){
  balls = (Ball[]) append(balls, new Ball(random(0,width),random(0,height)));
  }

void draw() {
  background(255);
  for (int i = 0; i < balls.length; i++) {
    balls[i].display();
    balls[i].move();
    balls[i].edges();
    for (int o = 0; o < balls.length; o++) {
      if (o!=i) {
        balls[i].overlaps(balls[o]);
        balls[o].overlaps(balls[i]);
      }
    }
  }
}
//creating the class and variables
class Ball {
  float dia;
  float x;
  float y; 
  float col;
  float xspeed;
  float yspeed;
  float r;

// 
  Ball (float tempD, float tempC) {
    x = random(100, 700);
    y = random(100, 400);
    dia = tempD;
    col = tempC;
    r = dia/2;
    xspeed = 7.0;
    yspeed = 4.0;
  }
 
  void display() {
    noStroke();
    fill(30,20,100);
    ellipse(x, y, dia, dia);
  }
 
  void move() {
    //xspeed = xspeed+acc;
    //yspeed = yspeed+acc;
    x = x + xspeed;
    y = y + yspeed;
  }
 
  void edges() {
    if (x > width-r ) {
      xspeed = abs(xspeed) * -1; // always neg
    }
    if ( x < r) {
      xspeed = abs(xspeed); // awlways pos
    }
    if (y > height-r ) {
      yspeed = abs(yspeed) * -1; // always neg
    }
    if ( y < r) {
      yspeed = abs(yspeed); // awlways pos
    }
  }
  void overlaps(Ball o) {
    float d = dist(x, y, o.x, o.y);
    if (d <= r + o.r) {
      if(x<o.x) {
      xspeed= -abs(xspeed);
      }
      if(x>o.x) {
      xspeed= abs(xspeed);
      }
      if(y<o.y) {
      yspeed= -abs(yspeed); 
      }
      if(y>o.y) {
      yspeed= abs(yspeed);
      }      
    }
  }
}
1 Like

If you add a debug statement into your loop in setup(), the problem gets obvious:

  for (int i = 0; i < balls.length; i++) {
    balls =  (Ball[])append(balls, new Ball(random(0, width), random(0, height)));
    println(balls.length);
  }

Since you are appending new elements inside of this loop, you will never meet the condition to break the loop: ā€œiā€ will always be 5 less than the array-size.

You can just assign the array values instead of appending them in setup():

  for (int i = 0; i < balls.length; i++) {
    balls[i] = new Ball(random(0, width), random(0, height));
  }

Regards.

2 Likes