82 lines
2.3 KiB
JavaScript
82 lines
2.3 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 高度() {
|
|
return height - this.position.y;
|
|
}
|
|
|
|
get 势能() {
|
|
return this.mass * this.gravity.y * this.高度;
|
|
}
|
|
|
|
get 速率() {
|
|
return this.velocity.mag();
|
|
}
|
|
|
|
get 动能() {
|
|
return 0.5 * this.mass * this.速率 ** 2;
|
|
}
|
|
|
|
get 机械能() {
|
|
return this.势能 + this.动能;
|
|
}
|
|
|
|
get 运动方向() {
|
|
return this.velocity.heading();
|
|
}
|
|
|
|
get finished() {
|
|
return this.life > 0 && this.duration >= this.life;
|
|
}
|
|
|
|
applyForce(force) {
|
|
this.acceleration.add(force.div(this.mass));
|
|
}
|
|
|
|
// 未完成
|
|
bounce(rate) {
|
|
if (this.position.x <= 0) {
|
|
this.position.x = 0;
|
|
this.velocity.x *= -1;
|
|
if (rate > 0) this.velocity.mult(rate);
|
|
} else if (this.position.x > width) {
|
|
this.position.x = width;
|
|
this.velocity.x *= -1;
|
|
if (rate > 0) this.velocity.mult(rate);
|
|
}
|
|
if (this.position.y <= 0) {
|
|
this.position.y = 0;
|
|
this.velocity.y *= -1;
|
|
if (rate > 0) this.velocity.mult(rate);
|
|
} else if (this.position.y >= height) {
|
|
this.position.y = height;
|
|
this.velocity.y *= -1;
|
|
if (rate > 0) this.velocity.mult(rate);
|
|
}
|
|
}
|
|
|
|
// 反弹算法未完成
|
|
move(bounce = false) {
|
|
// 重力加速度
|
|
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);
|
|
}
|
|
}
|