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
82 changes: 54 additions & 28 deletions GravityBallCode/GravityBallCode.pde
Original file line number Diff line number Diff line change
@@ -1,38 +1,64 @@
//declare variables
float x, y, velX, velY, diam;
int woof = 30;
float[] x = new float[woof];
float[] y = new float[woof];
float[] velX = new float[woof];
float[] velY = new float[woof];
float[] diam = new float[woof];
float[] gravity = new float[woof];
float[] friction = new float[woof];
float[] y2 = new float[woof];

void setup() {
//set size of canvas
void setup()
{
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 < woof; i++)
{
x[i] = random(width);
y[i]= random(height);
diam[i] = 50;
y2[i] = height - diam[i]/2;
velX[i] = random(-4.9, 5);
velY[i]= random(-4.9, 5);
gravity[i]= 0.4;
friction[i] = 0.95;
}
}

void draw() {
//draw background to cover previous frame
void draw()
{
background(0);
for(int i = 0;i < woof; i++)
{
noStroke();
fill(random(255),random(255),random(255));
ellipse(x[i], y[i], diam[i], diam[i]);

//draw ball
ellipse(x, y, diam, diam);

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

//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 (x[i] + diam[i]/2 >= width)
{
velX[i] = -abs(velX[i]);
} else if (x[i] - diam[i]/2 <= 0) {
velX[i] = abs(velX[i]);
}
if (y + diam/2 >= height) {
velY = -abs(velY);
} else if (y - diam/2 <= 0) {
velY = abs(velY);
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 (y[i]-diam[i]/2 > 0)
{
velY[i] = velY[i] + gravity[i];
}
if (y[i]+diam[i]/2 > height)
{
y[i] = y2[i];
}
if (y[i] + diam[i]/2 >= height)
{
velX[i] = velX[i] * friction[i];
}
}
}