Script for very simplistic bouncing mechanics & using classes
int number = 20;
int a = number-1;
int i;
Ball[] balls;
int rad=20;
void setup()
{
background (255);
size(500, 500);
noStroke();
fill(0);
balls = new Ball [number];
for (i = 0; i < number; i++)
{
balls[i] = new Ball(random(0, height), random(0, width), rad, rad, random(-2, 2), random(-2, 2), i, balls );
}
}
void draw()
{
background (0);
for (Ball bal : balls) {
bal.update();
bal.bounce();
bal.display();
}
}
class Ball
{
float b;
float c;
int sizex;
int sizey;
float incrementx;
float incrementy;
int id;
Ball[] others;
Ball(float btemp, float ctemp, int sizextemp, int sizeytemp, float incrementxtemp, float incrementytemp, int idtemp, Ball[] otherstemp)
{
b=btemp;
c=ctemp;
sizex=sizextemp;
sizey=sizeytemp;
incrementx=incrementxtemp;
incrementy=incrementytemp;
id=idtemp;
others=otherstemp;
}
void update()
{
if (b > width || b < 0)
{
incrementx=-incrementx;
}
if (c > height || c < 0)
{
incrementy=-incrementy;
}
b += incrementx; //add incrementX to posX
c += incrementy; //posY
}
void display()
{
fill(255);
ellipse(b, c, rad, rad);
}
void bounce()
{
int j;
for (j=id; j<number; j++)
{
float db= others[j].b – b;
float dc= others[j].c – c;
float distance = sqrt(db*db + dc*dc);
float minDist = others[j].sizex/2 + sizex/2;
if (distance < minDist)
{
incrementx =- incrementx;
others[j].incrementx =- others[j].incrementx;
incrementy =- incrementy;
others[j].incrementy =- others[j].incrementy;
b += incrementx;
others[j].b += others[j].incrementx;
c += incrementy;
others[j].c += others[j].incrementy;
}
}
}
}