
|
50 balls, with random sizes and velocities are bouncing within the boundaries of the screen. Using Object Oriented Programming, it is possible to reproduce easily the behavior of one element to a larger scale. |
// BOUNCE 2C, OBJECT ORIENTED, N BALLS
Ball[] myBalls;
int N = 50; // how many balls we want...
void setup()
{
size(200, 200);
framerate(25);
myBalls = new Ball[N];
for (int i = 0; i < N; i++)
{
myBalls[i] = new Ball();
myBalls[i].x = random(0, width);
myBalls[i].y = random(0, height);
myBalls[i].vx = random(-7, 7);
myBalls[i].vy = random(-7, 7);
myBalls[i].radius = random(3, 9);
}
}
void loop()
{
background(0);
for (int i = 0; i < N; i++)
{
myBalls[i].run();
}
}
class Ball
{
float x;
float y;
float vx;
float vy;
float radius;
void run()
{
drawShape();
x = x + vx;
y = y + vy;
// the following tests are keeping the ball within the boundaries of the screen, taking in count the radius of the ball
if (x < radius)
{
x = radius;
vx = -vx;
}
if (x > width - radius)
{
x = width - radius;
vx = -vx;
}
if (y < radius)
{
y = radius;
vy = -vy;
}
if (y > height - radius)
{
y = height - radius;
vy = -vy;
}
}
void drawShape()
{
ellipseMode(CENTER_RADIUS);
noStroke();
fill(255);
ellipse(x, y, radius, radius);
}
}