Daily Creative Coding

元「30 min. Processing」。毎日、Creative Codingします。

Bounding Balls with Gravity

/**
* Bounding Balls with Gravity
*
* @author aa_debdeb
* @date 2015/09/01
*/

ArrayList<Ball> balls;
int BALL_NUM = 10;
float BALL_DIAMETER = 50.0;
float BALL_RADIOUS = BALL_DIAMETER / 2.0;
float MAX_VX = 5.0;
float COEFFICIENT_REBOUND = 0.9;
float GRAVITY = -1.0;

void setup(){
  size(500, 500);
  noFill();
  smooth();
  background(255);  
  
  balls = new ArrayList<Ball>();
  for(int i = 0; i < BALL_NUM; i++){
    balls.add(new Ball());
  }
}

void draw(){
  background(255);
  for(Ball ball : balls){
    ball.draw();
  }
  for(Ball ball : balls){
    ball.update();
  }
}

class Ball{
  float x;
  float y;
  float vx;
  float vy;

  Ball(){
    x = random(width - BALL_DIAMETER) + BALL_RADIOUS;
    y = height + BALL_RADIOUS;
    vx = random(2.0 * MAX_VX) - MAX_VX;
    vy = 0.0;
  }   
  
  void draw(){
    stroke(0);
    strokeWeight(2.0);
    arc(x, height - y, BALL_DIAMETER, BALL_DIAMETER, 0, 2*PI);
  }
  
  void update(){
    
    x += vx;
    if(x <= BALL_RADIOUS || x >= width - BALL_RADIOUS){
      vx *= -1.0;
    }
    
    y += vy;
    if(y <= BALL_RADIOUS){
      vy = -vy * COEFFICIENT_REBOUND;
    } else {
        vy += GRAVITY;
    }
    
  }
}