Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
64 changes: 43 additions & 21 deletions GravityBallCode/GravityBallCode.pde
Original file line number Diff line number Diff line change
@@ -1,38 +1,60 @@
//declare variables
float x, y, velX, velY, diam;
int count=30;

float [] x = new float [count];
float [] y = new float [count];
float [] velx = new float [count];
float [] velY = new float [count];
float [] diam = new float [count];
float [] grav = new float [count];
void setup() {
//set size of canvas
size(800, 600);

//initialize variables
x = width/2;
y = height/2;
diam = 80;
velX = random(-5, 5);
velY = random(-5, 5);
for (int i=0; i < count; i++) {
x[i] = width/2;
y[i] = height/2;
diam[i] = random(50);
velx[i] = random(-5, 5);
velY[i] = random(-5, 5);
grav[i] = .2;
}
}

void draw() {
//draw background to cover previous frame
background(0);

//draw ball
ellipse(x, y, diam, diam);
for (int i=0; i <count; i++) {
velY[i] += grav[i];
fill(random(250),random(250),random(250));
ellipse(x[i], y[i], diam[i], diam[i]);
//add velocity to position
x[i] += velx[i];
y[i] += velY[i];

//add velocity to position
x += velX;
y += velY;

//bounce ball if it hits walls
if (x + diam/2 >= width) {
velX = -abs(velX); //if the ball hits the right wall, assign x velocity the negative version of itself
} else if (x - diam/2 <= 0) {
velX = abs(velX); //if the ball hits the left wall, assign x velocity the positive version of itself
}
if (y + diam/2 >= height) {
velY = -abs(velY);
} else if (y - diam/2 <= 0) {
velY = abs(velY);
//bounce ball if it hits walls
if (x[i] + diam[i]/2 >= width) {
velx[i] = -abs(velx[i]); //if the ball hits the right wall, assign x[0] velocity the negative version of itself
} else if (x[i] - diam[i]/2 <= 0) {
velx[i] = abs(velx[i]); //if the ball hits the left wall, assign x[0] velocity the positive version of itself
}
if (y[i] + diam[i]/2 >= height) {
velY[i] = -abs(velY[i]);
} else if (y[i] - diam[i]/2 <= 0) {
velY[i] = abs(velY[i]);
}
if (x[i] + diam[i] >= width) {
velx[i] = -abs(velx[i]); //if the ball hits the right wall, assign x[0] velocity the negative version of itself
} else if (x[i] - diam[i] <= 0) {
velx[i] = abs(velx[i]); //if the ball hits the left wall, assign x[0] velocity the positive version of itself
}
if (y[i]+ diam[i] >= height) {
velY[i] = -abs(velY[i]);
} else if (y[i] - diam[i] <= 0) {
velY[i] = abs(velY[i]);
}
}
}