我正在创建一个模拟5个相互坠落的自由落球的方法。我有碰撞检测并完成了碰撞。但是我在定义典型的自由落体方程时遇到了麻烦。我尝试了很多方法,但是我的知识非常有限。我也希望获得更好的编码实践的帮助。
let bola1;
let bola2;
let bola3;
let bola4;
let bola5;
class Bola{
constructor(y,r,v,m){
this.x = width/2;
this.y = y;
this.r = r;
this.v = v;
this.m = m;
this.a = -10;
}
veloci(){
this.y = this.y+this.v
}
show(){
ellipse(this.x, this.y, this.r,this.r);
}
reverse(){
this.v = -this.v
}
// floor
piso(){
return (this.y >= height)
}
// collide
choca(other){
return !(this.y+this.r< other.y ||this.y> other.y+other.r)
}
// bounce
rebota(other) {
let sumM = this.m + other.m;
let newV = (this.m - other.m) / sumM * this.v;
newV += (2 * other.m / sumM) * other.v;
return newV;
}
display() {
ellipse(this.x, this.y, this.diameter, this.diameter);
}
}
function setup() {
createCanvas(600, 500);
bola1 = new Bola(450,50,3,1);
bola2 = new Bola(350,50,3,1);
bola3 = new Bola(250,50,3,1);
bola4 = new Bola(150,50,3,1);
bola5 = new Bola(50,50,3,1);
}
function draw() {
background(110,20,20);
// Show and update velocity for each ball
// I would like to find a better way to handle these
bola1.show();
bola1.veloci();
bola2.show();
bola2.veloci();
bola3.show();
bola3.veloci();
bola4.show();
bola4.veloci();
bola5.show();
bola5.veloci();
// Make the ball bounce when it hits the floor
if (bola1.piso()) {
bola1.reverse();
}
// Attempt to make balls bounce when they collide with each other
if (bola1.choca(bola2)){
const v1 = bola1.rebota(bola2);
const v2 = bola2.rebota(bola1);
bola1.v = v1;
bola2.v = v2;
}
if (bola2.choca(bola3)){
const v3 = bola2.rebota(bola3);
const v4 = bola3.rebota(bola2);
bola2.v = v3;
bola3.v = v4;
}
if (bola3.choca(bola4)){
const v5 = bola3.rebota(bola4);
const v6 = bola4.rebota(bola3);
bola3.v = v5;
bola4.v = v6;
}
if (bola4.choca(bola5)){
const v7 = bola4.rebota(bola5);
const v8 = bola5.rebota(bola4);
bola4.v = v7;
bola5.v = v8;
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.7.3/p5.min.js"></script>
您还可以在此处查看代码: https://editor.p5js.org/yogurtcongelado/sketches/mxEJxtsU_
(如果您知道如何在p5中使用分隔的文件夹,因为如果尝试在班级中使用另一个文件夹,则主程序会说未定义对象)