let bodies = [];
let attractor;
function setup() {
createCanvas(800, 600);
for (let i = 0; i < 32; i++) {
bodies[i] = new Body(width/2, (10 + (i * 4)), 2, (4 + (i/32)), 0);
}
attractor = new Attractor(width/2, height/2, 256);
}
function draw() {
background(32, 64);
for (let i = 0; i < bodies.length; i++) {
for (let j = 0; j < bodies.length; j++) {
if (i !== j) {
let force = bodies[j].attract(bodies[i]);
bodies[i].applyForce(force);
}
}
let force = attractor.attract(bodies[i]);
bodies[i].applyForce(force);
bodies[i].update();
bodies[i].show();
}
}
class Attractor {
constructor(x, y, m) {
this.position = createVector(x, y);
this.mass = m;
}
attract(mover) {
let force = p5.Vector.sub(this.position, mover.position);
let distance = force.mag();
distance = constrain(distance, 5, 25);
let strength = (this.mass * mover.mass) / (distance * distance);
force.setMag(strength);
return force;
}
}
class Body {
constructor(x, y, mass, accX, accY) {
this.mass = mass;
this.position = createVector(x, y);
this.velocity = createVector(0, 0);
this.acceleration = createVector(accX, accY);
this.rC = random(100, 255);
this.gC = random(100, 255);
this.bC = random(100, 255);
}
applyForce(force) {
let f = p5.Vector.div(force, this.mass);
this.acceleration.add(f);
}
update() {
this.velocity.add(this.acceleration);
this.position.add(this.velocity);
this.acceleration.mult(0);
}
attract(body) {
let force = p5.Vector.sub(this.position, body.position);
let d = constrain(force.mag(), 32, 256);
let strength = ((this.mass * body.mass)) / (d * d);
force.setMag(strength);
return force;
}
show() {
noStroke();
fill(this.rC, this.gC, this.bC);
circle(this.position.x, this.position.y, this.mass * 6);
}
}