Make balls bounce

I am trying to make a project in which when a ball bounces against the edge of the screen, another ball is produced, and I will loop it. However, due to an error which seems almost impossible to fix, the second ball is not being produced. What should I do to improve my code?

Here is my code:

void setup(){
  size(1950,1050);
  float colour1, colour2, colour3;
  float ballsize = 50.0, ballx,bally, xspeed=5, yspeed=8;
}
void draw() {
  background(0);}
 
 
void generate() {
    fill(colour1, colour2, colour3);
    ellipse(ballx, bally, ballsize, ballsize);
}

void changeColour() {
    colour1 = random(255);
    colour2 = random(255);
    colour3 = random(255);
    generate(); 
}



void myball(){
  myball= new ball(ballx, bally, ballsize, ballsize);
  myball.createBall();
  myball.generate();
}


class Ball{
  generate(){
  createBall();{
  ellipse(ballx, bally, ballsize, ballsize); 

  if(side_collision(ballx)) {
    xspeed = xspeed*-1;
    ellipse(ballx, bally, ballsize, ballsize);
    changeColour()
    myball.create(){
    myball.generate(){
 new ellipse(ballx-xspeed, bally-yspeed, ballsize, ballsize);
  }
    }
    }
  }
  
  
  if(toporbottom_collision(bally)) {
    yspeed = yspeed*-1;
    ellipse(ballx, bally, ballsize, ballsize);
  changeColour();
  }
     {
 ballx = ballx +xspeed;
  bally = bally +yspeed;
}


boolean side_collision(float x) {
  if(x<0 || x>width) {
    return true;
  } else {
    return false;
  }
}

boolean toporbottom_collision(float y) {
  if (y<0 || y>height){
    return true;
  } else {
    return false;
  }
  
}

}
1 Like

please format your code posting by pasting it into the

</> code button

of the editor header menu ( context name: Preformatted text )
it looks like
```
type or paste code here
```

also can use the ``` manually above and below your code.

thank you.


3 Likes

First of all… what languague is that?? It doesn‘t seem like Java, nor P5.js or py… Also, what is your class Ball supposed to do? Especially the beginning seems not like any valid code syntax (at least none i know…). Please add some information and format your Code.

I think it will help to study the Object tutorial: https://processing.org/tutorials/objects/.

Once you’ve read it, I recommend to start a new sketch and start out really simple. Only try to display a ball on your screen by using a class. It doesn’t need to be moving, nor have random colours; just make sure your class is working. Once your class works, then you could add more methods such as movement and bouncing.

2 Likes

Hi there! Would be happy to help you, however, got really confused as I couldn’t really understand, what language you’re using… Could you specify that one, please?