xxxxxxxxxx
97
let particles = [];
function setup() {
createCanvas(400, 400);
background(255, 240, 220);
makeParticles(100);
}
function draw() {
background(255, 240, 220);
updateAndDrawParticles();
}
function updateAndDrawParticles() {
for (let i = particles.length-1; i >= 0; i--) {
if (particles[i].dead) {
particles.splice(i, 1);
} else {
particles[i].updateMe();
particles[i].drawMe();
}
}
}
function randColor() {
let r = random(256);
let g = random(256);
let b = random(256);
let result = color(r, g, b, 128);
return result;
}
function makeParticles(num) {
for (let i = 0; i < num; i++) {
let p = {
x: random(width),
y: random(height),
rad: random(5, 8),
fillColor: randColor(),
velX: random(-2, 2),
velY: random(-2, 2),
lifespan: floor(random(60, 200)),
age: 0,
dead: false,
drawMe: function () {
noStroke();
fill(this.fillColor);
ellipseMode(RADIUS);
circle(this.x, this.y, this.rad);
},
updateMe: function () {
this.age += 1;
if (this.age > this.lifespan) {
this.dead = true;
}
if (this.dead) {
this.fillColor = color(0, 0, 0, 128);
}
this.x = this.x + this.velX;
this.y = this.y + this.velY;
this.velX += random(-0.5, 0.5);
this.velY += random(-0.5, 0.5);
if (this.velX > 4) {
this.velX = 4;
} else if (this.velX < -4) {
this.velX = -4;
}
if (this.velY > 4) {
this.velY = 4;
} else if (this.velY < -4) {
this.velY = -4;
}
// handle bouncing
if (this.x > width - this.rad) {
this.x = width - this.rad;
this.velX = -this.velX;
} else if (this.x < this.rad) {
this.x = this.rad;
this.velX = -this.velX;
}
if (this.y > height - this.rad) {
this.y = height - this.rad;
this.velY = -this.velY;
} else if (this.y < this.rad) {
this.y = this.rad;
this.velY = -this.velY;
}
},
};
particles.push(p);
}
}