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);
}
}
}
}