xxxxxxxxxx
44
let bod1;
let bod2 = [];
const G = 0.0001;
function setup() {
createCanvas(600, 600);
bod1 = {
pos: createVector(width / 2, height / 2),
vel: createVector(2, 1)
};
for (let i = 0; i < 10; i++) {
bod2[i] = {
pos: createVector(random(0, width), random(0, height)),
mass: random(1, 5)
};
}
}
function draw() {
background(220);
// Draw bod1
ellipse(bod1.pos.x, bod1.pos.y, 30, 30);
// Draw bod2
for (let bod of bod2) {
ellipse(bod.pos.x, bod.pos.y, 30, 30);
}
// Update velocities
for (let bod of bod2) {
const direction = p5.Vector.sub(bod.pos, bod1.pos);
const distanceSq = direction.magSq();
const forceMagnitude = (G * bod.mass) / distanceSq;
const force = direction.normalize().mult(forceMagnitude);
bod1.vel.add(force);
}
// Update positions
bod1.pos.add(bod1.vel);
}