2022-12-11 13:52:13 +00:00
|
|
|
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;
|
2022-12-11 15:34:40 +00:00
|
|
|
this.size = 2;
|
2022-12-11 13:52:13 +00:00
|
|
|
this.lifetime = 0;
|
2022-12-11 15:34:40 +00:00
|
|
|
this.endtime = 5;
|
2022-12-11 13:52:13 +00:00
|
|
|
}
|
|
|
|
|
2022-12-11 15:34:40 +00:00
|
|
|
lifeover() {
|
|
|
|
return this.lifetime >= this.endtime;
|
|
|
|
}
|
|
|
|
|
|
|
|
update(force) {
|
|
|
|
if (this.lifeover()) return;
|
2022-12-11 13:52:13 +00:00
|
|
|
// 计算加速度
|
|
|
|
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() {
|
2022-12-11 15:34:40 +00:00
|
|
|
if (this.lifeover()) return;
|
2022-12-11 13:52:13 +00:00
|
|
|
noStroke();
|
|
|
|
fill(this.hue, this.saturation, this.brightness, this.alpha);
|
|
|
|
circle(this.position.x, this.position.y, this.size);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
class Particles {
|
2022-12-11 15:34:40 +00:00
|
|
|
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();
|
|
|
|
});
|
|
|
|
}
|
2022-12-11 13:52:13 +00:00
|
|
|
}
|