From 99d8b9c9d044ab36de386fe95c374b6f2404efcc Mon Sep 17 00:00:00 2001 From: shivani517 Date: Fri, 13 Nov 2015 12:15:56 -0500 Subject: [PATCH] Multiple Balls have gravity --- GravityBallCode/GravityBallCode.pde | 67 ++++++++++++++++++----------- 1 file changed, 41 insertions(+), 26 deletions(-) diff --git a/GravityBallCode/GravityBallCode.pde b/GravityBallCode/GravityBallCode.pde index df2493b..37f525c 100644 --- a/GravityBallCode/GravityBallCode.pde +++ b/GravityBallCode/GravityBallCode.pde @@ -1,38 +1,53 @@ //declare variables -float x, y, velX, velY, diam; - +float[] x= new float [30]; +float[] y= new float [30]; +float[] velX= new float [30]; +float[] velY= new float [30] ; +float diam; +float a; 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<30; i++) { + //initialize variables + x[i] = random(450); + y[i] = random(100); + diam = 30; + velX[i] =5; + velY[i] = 5; + a=1; + } } void draw() { //draw background to cover previous frame - background(0); + background(255); + for (int i=0; i<30; i++) { - //draw ball - ellipse(x, y, diam, diam); + //draw ball + fill(255, 204, 255); + ellipse(x[i], y[i], diam, diam); + velY[i] += a; + //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/2 >= width) { + velX[i] = -abs(velX[i]); //if the ball hits the right wall, assign x velocity the negative version of itself + } else if (x[i] - diam/2 <= 0) { + velX[i] = abs(velX[i]); //if the ball hits the left wall, assign x velocity the positive version of itself + } + if (y[i] + diam/2 >= height) { + y[i]=height- diam/2; + velY[i] = -abs(velY[i]); + } else if (y[i] - diam/2 <= 0) { + velY[i] = abs(velY[i]); + } + if (dist(x[i], y[i], mouseX, mouseY) <= diam/2 && height>= 0) { + fill(210, 217, 255); + velX[i]= -abs(velX[i]); + velY[i]= -abs(velY[i]); + } } } \ No newline at end of file