xxxxxxxxxx
80
var NUM_BALLS = 10;
var balls = [];
function setup() {
createCanvas(windowWidth, windowHeight);
noStroke()
// create the balls
for (var ballNum = 0; ballNum < NUM_BALLS; ballNum++) {
balls[ballNum] = new Ball();
}
}
function draw() {
background(255);
// cycle though each ball
for (var ballNum = 0; ballNum < balls.length; ballNum++) {
// draw the current ball
balls[ballNum].display();
// check to see if it collided with a wall
balls[ballNum].checkForHit();
// move it
balls[ballNum].moveBall();
// if the mouse is pressed, wiggle
if (mouseIsPressed) {
balls[ballNum].randomize()
}
}
}
// Ball object
class Ball { // Constructor
constructor() {
// initial position
this.ballX = random(100, width)
this.ballY = random(100, height)
// Dictates velocity + direction
this.speedY = random(-5, 5);
this.speedX = random(-5, 5);
this.size = random(100);
// How transparent the ball is
this.alpha = 100
// RGB values for color
this.red = random(255);
this.green = random(255);
this.blue = random(255)
}
display() {
fill(this.red, this.green, this.blue, this.alpha);
ellipse(this.ballX, this.ballY, this.size);
}
randomize() {
this.speedY = random(-5, 5);
this.speedX = random(-5, 5);
}
checkForHit() {
if (this.ballY > height || this.ballY < 0) {
this.speedY = -this.speedY;
}
if (this.ballX > width || this.ballX < 0) {
this.speedX = -this.speedX;
}
}
moveBall() {
this.ballX += this.speedX;
this.ballY += this.speedY;
}
}