class Ball {
// Attributes
float x, y; // location
float r; // radius in pixels
color c; // color
float dx, dy; // speed
Box b; // the box the ball is in
// Constructor(s)
Ball(Box b) {
this(random(width), random(height), 25, color(0), b);
} // Ball()
Ball(Box b, color c) {
this(random(width), random(height), 25, c, b);
} // Ball()
Ball(float x, float y, float r, color c, Box b) {
this.b = b;
this.r = r;
this.x = x;
this.y = y;
this.c = c;
this.dx = random(-3, 3);
this.dy = random(-3, 3);
} // Ball()
// Behaviors
void display() {
noStroke();
fill(this.c);
circle(this.x, this.y, 2*this.r);
} // display()
void move() {
x = x + dx;
y = y + dy;
bounce();
} // move()
void bounce() {
float bw = b.getWidth();
float bh = b.getHeight();
if (x > bw-r) {
dx = -dx;
x = bw-r;
}
if (x < r) {
dx = -dx;
x = r;
}
if (y > bh-r) {
dy = -dy;
y = bh-r;
}
if (y < r) {
dy = -dy;
y = r;
}
} // bounce()
} // class Ball