xxxxxxxxxx
47
let balls = []; //array of objects of the class Balls
function setup() {
createCanvas(600, 600);
blendMode(LIGHTEST); //changed the blend mode to make it look better
}
function draw() {
fill(0);
rect(0, 0, width, height); //using a black rectangle instead of background to allow each ball to leave a trail
for (let i = 0; i < balls.length; i++) {
balls[i].drawBall();
}
}
function mouseClicked() { //each mouse click generates one ball on each side of the canvas
let ballRadius = random(5, 25); //random size
balls.push(new Ball(0 + ballRadius, mouseY, ballRadius));
balls.push(new Ball(width - ballRadius, mouseY, ballRadius));
}
class Ball {
constructor(x, y, radius){
this.x = x;
this.y = y;
this.colour = color(random(255), random(255), random(255)); //generate random colour of ball
if (this.x < 200) { //if the ball is generated on the left side of the canvas
this.speedX = 2; //makes the ball move in the correct direction depeneding on where it was spawned
} else {
this.speedX = -2;
}
this.timeStarted = millis(); //records the time the object was made
this.radius = radius;
}
drawBall() { //function to draw the ball
fill(this.colour);
circle(this.x, this.y, this.radius);
this.moveBall();
}
moveBall() { //function to update the ball's position
this.x += this.speedX;
this.y += (millis() - this.timeStarted) / 1000; //changes y depending on how much time has elapsed since the object was created to simulate downwards acceleration
}
}