I need help with a project

Hello! I have made a sketch with bouncing balls, where every time i click, a new ball appears. I want every new ball to have a random colour. Thank you!

//GLOBAL VARIABLES
Ball myBall;
Text myText;
Cursor myCursor;
final static ArrayList<Ball> balls = new ArrayList();

//CLASSES


//BALL CLASS
class Ball {
  float x, y;
  float speedX=5;
  float speedY=5;
  Ball(float _x, float _y) {
    x=_x;
    y=_y;
  }
  void run() {
    display();
    move();
    bounce();
    hit();
  }
  void bounce() {
    if (x>width || x<0) {
      speedX=speedX*-1;
    } else if (y>height || y<0) {
      speedY=speedY*-1;
    }
  }
  void move() {
    x+=speedX;
    y+=speedY;
  }
  void display() {
    ellipse(x, y, 15, 15);
  }
  void hit() {
    if (x>width ||x<0 ||y>height || y<0) {
      hit.play();
      myText.ballHit += 1;
    }
  }
}


//TEXT CLASS
class Text {
  int ballHit = 0;
  int spawnedBalls = 0;
  void drawText() {
    text("The balls have hit the border " + ballHit + " times", 25, 25);
    text("There are a total of " + spawnedBalls + " balls", 25, 50);
  }
}


//CURSOR CLASS
class Cursor {
  void drawCursor() {
    ellipse(mouseX,mouseY,25,25);
  }
}

void setup() {
  size(600, 600);
  smooth();
  fill(0);
  myBall=new Ball(0, 0);
  myText=new Text();
  myCursor=new Cursor();
}


void draw() { //MAIN CODE HERE
  background(#FFFFFF);
  for (Ball b : balls)   b.run();
  myText.drawText();
  myCursor.drawCursor();
}


void mousePressed() {
  balls.add(new Ball(mouseX, mouseY));
  myText.spawnedBalls += 1;
}```

To start with you could add a new color attribute to the Ball class (e.g. color c). Accordingly update the constructor to take a color parameter: Ball(float _x, float _y, color _c)
Finally in the display function you can add stroke(c) or fill(c) to color the outline or fill of the ball.
Now you can send in a random color every time you create a new ball like so:
new Ball(mouseX, mouseY, color(random(255),random(255),random(255)))

3 Likes

Thank you so much kind sir

1 Like