xxxxxxxxxx
85
const G = 0.01 //Gravitational constant
const density = 4
function gravitate(body1, body2, minD=1, maxD=99999) {
//d = p5.Vector.dist(body1.pos, body2.pos);
let g_dir = p5.Vector.sub(body2.pos, body1.pos);
let d = g_dir.mag()
if (d >= maxD) {
return createVector(0,0,0);
}
if (d <= minD) {
body1.collisions++
body2.collisions++
return p5.Vector.sub(body1.pos, body2.pos).setMag(body1.r)
}
let g_mag = G*(body1.m*body2.m)/(d*d);
return g_dir.setMag(g_mag);
}
class Orb {
constructor(x,y,z,mass,id) {
this.id = id
this.m = mass;
this.r = sqrt(mass)/density;
this.gravity_rad = 100;
this.pos = createVector(x,y,z);
this.vel = createVector(0,0,0);
this.acc = createVector(0,0,0);
this.collisions = 0;
}
show() {
let r = this.collisions*100;
push();
stroke(r, r/4, r/2);
strokeWeight(this.r*2);
point(this.pos.x, this.pos.y, this.pos.z);
pop();
}
update() {
this.vel.add(this.acc);
this.pos.add(this.vel);
this.collisions*=0.9999
}
gravitate_grp(grp) {
for (let o of grp) {
if (o.id!=this.id) {
o.acc.sub(gravitate(this, o, this.r, width));
}
}
}
}
let orbs = []
let n_orbs = 600
function setup() {
createCanvas(400, 400, WEBGL);
for (let i=0;i<n_orbs;i++) {
orbs.push(new Orb(x=random(width)-width/2,
y=random(height)-height/2,
z=-3000+random(100),
mass=20,
id=i))
}
frameRate(20);
}
function draw() {
background(240);
for (let o of orbs) {
o.acc.mult(0)
}
for (let o of orbs) {
o.gravitate_grp(orbs)
}
for (let o of orbs) {
o.update();
o.show();
}
if (frameCount > 100) {
//noLoop();
//console.log("Complete")
}
}