xxxxxxxxxx
50
var balls = [];
var ballWidth = 30;
var dlife = 0.6;
function setup() {
createCanvas(640, 360);
balls.push(new Ball(width / 2, 0, ballWidth)); // add first ball
}
function draw() {
background(200, 200, 0);
for (let i = 0; i < balls.length; i++) {
balls[i].move();
if (balls[i].finished()) balls.splice(i, 1); // like @hotfooted
}
}
function mousePressed() {
balls.push(new Ball(mouseX, mouseY, random(5, ballWidth))); // Add new ball object to Array
}
class Ball { // Simple bouncing ball class
constructor(tempX, tempY, tempW) {
this.x = tempX;
this.y = tempY;
this.w = tempW;
this.speed = 0;
this.gravity = 0.1;
this.life = 255.0; // used also as ALPHA for fill
}
move() { // Add gravity to speed
this.speed = this.speed + this.gravity;
this.y = this.y + this.speed; // Add speed to y location
if (this.y + this.w > height) { // If ball reaches the bottom Reverse speed
this.speed = this.speed * -0.8; // Dampening
this.y = height - this.w; // anti rebounce
}
this.life -= dlife; // grow old
fill(0, 0, 200, this.life); // fading
stroke(0, 200, 0); // not fading, gone when dead
circle(this.x, this.y, this.w);
}
finished() {
if (this.life < 0) return true;
else return false;
}
}