// The Ball class models ball objects
// Each Ball has several attributes:
// location, size, color, and how it moves
class Ball {
// Attributes
float x, y; // location
float radius; // its size
color ballColor; // Ball color
float dx;
float dy;
// Constructor(s)
Ball() {
radius = 25;
x = random(radius, width-radius);
y = random(radius, height-radius);
ballColor = color(255, 0, 0);
dx = random(4);
dy = random(4);
} // Ball()
// Create a ball with given radius and color
Ball(float r, color c) {
radius = r;
x = random(radius, width-radius);
y = random(radius, height-radius);
ballColor = c;
dx = random(4);
dy = random(4);
} // Ball()
// Behaviors
void display() {
noStroke();
fill(ballColor);
circle(x, y, 2 * radius);
} // display()
void move() {
x = x + dx;
y = y + dy;
bounce();
} // move()
void bounce() {
if (x > width-radius) {
dx = -dx;
}
if (x < radius) {
dx = -dx;
}
if (y > height-radius) {
dy = -dy;
}
if (y < radius) {
dy = -dy;
}
} // bounce()
void collide(Ball b) {
if (dist(x, y, b.x, b.y) <= (radius+b.radius)) {
dx = -dx;
dy = -dy;
b.dx = -b.dx;
b.dy = -b.dy;
}
} // collide()
} // class Ball