p5js/particle.js

39 lines
1.1 KiB
JavaScript
Raw Normal View History

2022-12-11 13:52:13 +00:00
class Particle {
constructor(x, y) {
this.position = createVector(x, y);
this.velocity = createVector(0, 0);
this.gravity = createVector(0, 10); // G = 9.81
2022-12-12 12:04:55 +00:00
this.acceleration = createVector(0, 0);
this.duration = 0;
this.life = 1;
this.mass = 1;
2022-12-11 13:52:13 +00:00
}
2022-12-12 12:04:55 +00:00
get heading() {
return this.velocity.heading();
2022-12-11 13:52:13 +00:00
}
2022-12-12 12:04:55 +00:00
get finished() {
return this.duration >= this.life;
2022-12-11 15:34:40 +00:00
}
2022-12-12 12:04:55 +00:00
applyForce(force) {
this.acceleration.add(force.div(this.mass));
2022-12-11 15:34:40 +00:00
}
update() {
2022-12-12 12:04:55 +00:00
// 重力加速度
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);
2022-12-11 15:34:40 +00:00
}
2022-12-11 13:52:13 +00:00
}