class Particle { constructor(x, y) { this.mass = 1; this.position = createVector(x, y); this.velocity = createVector(0, 0); this.gravity = createVector(0, 10); // G = 9.81 this.hue = 0; this.saturation = 0; this.brightness = 100; this.alpha = 1; this.size = 2; this.lifetime = 0; this.endtime = 5; } lifeover() { return this.lifetime >= this.endtime; } update(force) { if (this.lifeover()) return; // 计算加速度 const acceleration = createVector(0, 0); acceleration.add(this.gravity); if (force) acceleration.add(force.div(this.mass)); // 计算时间差 const duration = deltaTime / 1000; this.lifetime += duration; // 计算速度差及位移 const deltaVelocity = acceleration.mult(duration); const averageVelocity = deltaVelocity.copy().div(2).add(this.velocity); const movement = averageVelocity.mult(duration); // 更新速度及位置 this.velocity.add(deltaVelocity); this.position.add(movement); } show() { if (this.lifeover()) return; noStroke(); fill(this.hue, this.saturation, this.brightness, this.alpha); circle(this.position.x, this.position.y, this.size); } } class Particles { constructor(x, y, n) { this.particles = []; for (let i = 0; i < n; i++) { const p = new Particle(x, y); this.particles.push(p); } } lifeover() { return this.particles.length === 0; } update() { this.particles.forEach((p, i) => { if (p.lifeover()) { this.particles.splice(i, 1); } else { p.update(); } }); } show() { this.particles.forEach((p) => { p.show(); }); } }