body {
margin: 0;
padding: 0;
}
cp_embed_wrapper {
width: 400;
height: 400;,
}
let stars;
let planet;
const limitSpeed = true;
const canvasWidth = 450;
const canvasHeight = 150;
function setup() {
createCanvas(canvasWidth, canvasHeight);
stars = [];
for (let i = 0; i < 3; i++) {
const star = createBody(random(width), random(height), 300);
star.setColor("yellow");
star.setSize(30);
stars.push(star);
}
planet = createBody(random(width), random(height), 0.001);
planet.setColor("blue");
planet.setSize(10);
}
function draw() {
background(150);
for (let i = 0; i < 3; i++) {
for (let j = 0; j < 3; j++) {
if (i !== j) {
stars[j].attract(stars[i]);
}
}
stars[i].update();
stars[i].show();
stars[i].attract(planet);
}
planet.update();
planet.show();
}
function createBody(x, y, mass) {
const position = createVector(x, y);
const velocity = createVector(0, 0);
const acceleration = createVector(0, 0);
const G = 0.001;
let fillColor = "white";
let size = 50;
const applyForce = (force) => {
const a = p5.Vector.div(force, mass);
acceleration.add(a);
};
const attract = (body) => {
const force = p5.Vector.sub(position, body.position);
let distance = force.mag();
if (limitSpeed) {
distance = constrain(distance, 5, 25);
}
let strength = (G * mass * body.mass) / (distance * distance);
force.setMag(strength);
body.applyForce(force);
};
const update = () => {
velocity.add(acceleration);
position.add(velocity);
acceleration.mult(0);
};
const show = () => {
stroke(0);
fill(fillColor);
circle(position.x, position.y, size);
};
const setColor = (c) => {
fillColor = c;
};
const setSize = (s) => {
size = s;
};
return {
position,
mass,
applyForce,
attract,
update,
show,
setColor,
setSize
};
}
This Pen doesn't use any external CSS resources.