xxxxxxxxxx
132
// Array to store partciles on the screen
let particles = [];
const colors = ['#FF6B6B', '#4ECDC4', '#45B7D1', '#FFA07A', '#98D8C8', '#F7DC6F', '#BB8FCE'];
class Particle {
constructor(x, y, size, color) {
this.x = x;
this.y = y;
this.size = size;
this.color = color;
this.speed = random(2, 5);
this.angle = random(TWO_PI);
// How long particle will be displayed on the screen
this.lifespan = random(150, 300);
this.alive = true;
this.explosionParticles = [];
this.explosionDuration = 60; // frames the explosion lasts
}
update() {
if (this.alive) {
if (this.lifespan > 0) {
// Move the particle
this.x += cos(this.angle) * this.speed;
this.y += sin(this.angle) * this.speed;
this.lifespan--;
// Wrap around edges
if (this.x < 0) this.x = width;
if (this.x > width) this.x = 0;
if (this.y < 0) this.y = height;
if (this.y > height) this.y = 0;
} else {
// If particle reached end of life, explode
this.explode();
}
} else {
// Update explosion animationa
this.updateExplosion();
}
}
display() {
if (this.alive) {
// Display main particle
noStroke();
fill(this.color);
ellipse(this.x, this.y, this.size);
} else {
// Display explosion particles
this.displayExplosion();
}
}
explode() {
this.alive = false;
for (let i = 0; i < 20; i++) {
// Create 20 small particles for explosion effect
this.explosionParticles.push({
x: this.x,
y: this.y,
// Random x, y velocity and random size
vx: random(-2, 2),
vy: random(-2, 2),
size: random(1, 5),
});
}
}
updateExplosion() {
if (this.explosionDuration > 0) {
for (let p of this.explosionParticles) {
p.x += p.vx;
p.y += p.vy;
p.size *= 0.95; // shrink particles over the time
}
this.explosionDuration--;
} else {
this.explosionParticles = []; // clear explosion particles
}
}
displayExplosion() {
for (let p of this.explosionParticles) {
noStroke();
fill(this.color);
ellipse(p.x, p.y, p.size);
}
}
// Check if the particle and its explosion are completely finished
isFinished() {
return !this.alive && this.explosionDuration <= 0;
}
}
function setup() {
createCanvas(800, 600);
// Initial set of particles
for (let i = 0; i < 50; i++) {
let x = random(width);
let y = random(height);
let size = random(5, 20);
let color = random(colors);
particles.push(new Particle(x, y, size, color));
}
}
function draw() {
// Semi-transparent background for trail effect
background(30, 30, 40, 20);
// Update and display all particles every frame
for (let particle of particles) {
particle.update();
particle.display();
}
// Remove finished particles
particles = particles.filter((p) => !p.isFinished());
// Add new particles every 5 frames
if (frameCount % 5 === 0) {
let x = random(width);
let y = random(height);
let size = random(5, 20);
let color = random(colors);
particles.push(new Particle(x, y, size, color));
}
}