Daily Creative Coding

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

A Rebounding Ball

/**
* A Rebounding Ball
*
* @author aa_debdeb
* @date 2015/08/29
*/

Ball ball;
float BALL_MAX_SPEED = 20.0;
float BALL_DIAMETER = 50.0;

void setup(){
  size(300, 300);
  smooth();
  background(255);
  frameRate(60);
  
  ball = new Ball();
}

void draw(){
  background(255);
  ball.draw();
  ball.update();
}

class Ball {
  float x;
  float y;
  float vx;
  float vy;
  float diameter;
  
  Ball(){
    x = width / 2.0;
    y = height / 2.0;
    vx = random(1) * BALL_MAX_SPEED - BALL_MAX_SPEED / 2.0;
    vy = random(1) * BALL_MAX_SPEED - BALL_MAX_SPEED / 2.0;
    diameter = BALL_DIAMETER;
  }
  
  void draw(){
    noStroke();
    fill(255, 0, 0); 
    arc(x, y, diameter, diameter, 0, 2.0*PI);
  }
  
  void update(){
    x += vx;
    y += vy;
    float radious = diameter / 2.0;
    if(x < radious){
      x = radious;
      vx *= -1.0;
    } else if (x > width - radious){
      x = width - radious;
      vx *= -1.0;
    }
    if(y < radious){
      y = radious;
      vy *= -1.0;
    } else if(y > height - radious){
      y = height - radious;
      vy *= -1.0;
    }
  }
  
}