xxxxxxxxxx
const G = 1;
const objs = [
[50,130,0,0,1],
[150,230,0,0,1],
[360,330,0,0,1],
[240,260,0,0,1],
[180,30,0,0,1],
];
var add = function(x,y,vx,vy,mass){
objs.push([x,y,vx,vy,mass]);
}
const step = function(dt){
//console.log(dt);
for(let i = 0; i < objs.length; i++){
for(let j = i+1; j < objs.length; j++){
//bidirectional
const o1 = objs[i];
const o2 = objs[j];
const dx = o2[0]-o1[0];
const dy = o2[1]-o1[1];
const dist2 = dx*dx+dy*dy;
const dist = Math.sqrt(dist2);
const rr = 10+10;
if(dist < rr){
const alphal = ((o1[2]-o2[2])*dx+(o1[3]-o2[3])*dy)/(dx*dx+dy*dy)/2*0.95;
const alphax = alphal*dx;
const alphay = alphal*dy;
o1[2] = o1[2]-2*alphax;
o1[3] = o1[3]-2*alphay;
o2[2] = o2[2]+2*alphax;
o2[3] = o2[3]+2*alphay;
//move them away on the collision axis
const penetration = (rr-dist)/dist;
const xm = dx*penetration/2;
const ym = dy*penetration/2;
o1[0] += -xm;
o1[1] += -ym;
o2[0] += xm;
o2[1] += ym;
continue;
}
const acc1 = G*o2[4]/dist2;
const acc1x = acc1*(dx/dist);
const acc1y = acc1*(dy/dist);
o1[2]+= acc1x*dt;
o1[3]+= acc1y*dt;
const acc2 = G*o1[4]/dist2;
const acc2x = acc2*(-dx/dist);
const acc2y = acc2*(-dy/dist);
o2[2]+= acc2x*dt;
o2[3]+= acc2y*dt;
}
}
for(let i = 0; i < objs.length; i++){
const o = objs[i];
o[0] += o[2]*dt;
o[1] += o[3]*dt;
}
};
function setup() {
createCanvas(400, 400);
stroke(0,0,0,0);
fill(0,0,0);
}
function draw() {
background(255);
const steps = 10;
for(let i = 0; i < steps; i++){
step(1);
}
for(let i = 0; i < objs.length; i++){
const o = objs[i];
circle(o[0],o[1],20);
}
}