p5js/particle.js
2022-12-12 20:04:55 +08:00

39 lines
1.1 KiB
JavaScript

class Particle {
constructor(x, y) {
this.position = createVector(x, y);
this.velocity = createVector(0, 0);
this.gravity = createVector(0, 10); // G = 9.81
this.acceleration = createVector(0, 0);
this.duration = 0;
this.life = 1;
this.mass = 1;
}
get heading() {
return this.velocity.heading();
}
get finished() {
return this.duration >= this.life;
}
applyForce(force) {
this.acceleration.add(force.div(this.mass));
}
update() {
// 重力加速度
this.acceleration.add(this.gravity); // G = 9.81
// 计算时间差
const duration = deltaTime / 1000; // 秒
this.duration += duration;
// 计算速度差及位移
const deltaVelocity = this.acceleration.mult(duration);
const averageVelocity = deltaVelocity.copy().div(2).add(this.velocity);
const displacement = averageVelocity.mult(duration);
// 更新速度及位置
this.velocity.add(deltaVelocity);
this.position.add(displacement);
}
}