> show canvas only <


/* built with Studio Sketchpad: 
 *   https://sketchpad.cc
 * 
 * observe the evolution of this sketch: 
 *   https://studio.sketchpad.cc/sp/pad/view/ro.PDJSatD2nvB/rev.126
 * 
 * authors: 
 *   Gisela Martiz
 *   Gen Green

 * license (unless otherwise specified): 
 *   creative commons attribution-share alike 3.0 license.
 *   https://creativecommons.org/licenses/by-sa/3.0/ 
 */ 



int numBalls = 13;  
//int declares numBalls as 15 (assigning it a value type)
float spring = 0.05;  
//float is a continuous value, 
float gravity = 0.05;  
Ball[] balls = new Ball[numBalls];  
//[] gives you access to the array - variable name[] access  

void setup()   
{  
  size(450, 450);  
  noStroke();  
  //means no outline
  smooth();  
  //all drawn with smooth edges
  for (int i = 0; i < numBalls; i++) {  
    balls[i] = new Ball(random(width), random(height), random(75, 40), i, balls);  
  }  
}  
 //Controls a sequence of repetitions. A for structure has three parts: init, test, and update. Each part must be separated by a semi-colon ";". The loop continues until the test evaluates to false.   Between the brackets are the statements
  
  
void draw()   
{  
  background(35, 89, 35);  
  for (int i = 0; i < numBalls; i++) {  
    balls[i].collide();  
    balls[i].move();  
    balls[i].display();    
  }  
}  
  
class Ball {  
  float x, y;  
  float diameter;  
  float vx = 0; 
  //throws  to the right
  float vy = 0;  
  int id;  
  Ball[] others;  
   
  Ball(float xin, float yin, float din, int idin, Ball[] oin) {  
    x = xin;  
    y = yin;  
    diameter = din;  
    id = idin;  
    others = oin;  
  }   
    
  void collide() {  
    for (int i = id + 1; i < numBalls; i++) {  
      float dx = others[i].x - x;  
      float dy = others[i].y - y;  
      float distance = sqrt(dx*dx + dy*dy);  
      float minDist = others[i].diameter/2 + diameter/2;  
      if (distance < minDist) {   
        float angle = atan2(dy, dx);  
        float targetX = x + cos(angle) * minDist;  
        float targetY = y + sin(angle) * minDist;  
        float ax = (targetX - others[i].x) * spring;  
        float ay = (targetY - others[i].y) * spring;  
        vx -= ax;  
        vy -= ay;  
        others[i].vx += ax;  
        others[i].vy += ay;  
      }  
    }     
  }  
    
  void move() {  
    vy += gravity;  
    x += vx;  
    y += vy;  
    if (x + diameter/2 > width) {  
      x = width - diameter/2;  
      vx += -0.9;   
    }  
    else if (x - diameter/2 < 0) {  
      x = diameter/2;  
      vx *= -0.9;  
    }  
    if (y + diameter/2 > height) {  
      y = height - diameter/2;  
      vy *= -0.9;   
    }   
    else if (y - diameter/2 < 0) {  
      y = diameter/2;  
      vy *= -0.9;  
    }  
  }  
    
  void display() {  
  fill(255, 204);  
    ellipse(x, y, diameter, diameter);  
  }  
}