xxxxxxxxxx
76
// Constants
const G = 1; // Gravitational constant
// Array to hold all the celestial bodies
let bodies = [];
// Body class
class Body {
constructor(x, y, mass) {
this.position = createVector(x, y);
this.velocity = createVector(0, 0);
this.acceleration = createVector(0, 0);
this.mass = mass;
}
applyForce(force) {
// Newton's second law: F = ma, therefore a = F/m
this.acceleration.add(force.div(this.mass));
}
update() {
// Update velocity and position using Verlet integration
this.velocity.add(this.acceleration);
this.position.add(this.velocity);
this.acceleration.mult(0); // Reset acceleration for next iteration
}
display() {
fill(255);
noStroke();
ellipse(this.position.x, this.position.y, this.mass * 5, this.mass * 5);
}
}
// Setup function
function setup() {
createCanvas(800, 600);
// Create some celestial bodies
bodies.push(new Body(width / 2, height / 2, 1000)); // Central massive body
bodies.push(new Body(width / 2 + 200, height / 2, 10)); // Small body orbiting the central body
}
// Draw function
function draw() {
background(0);
// Calculate gravitational forces between all pairs of bodies
for (let i = 0; i < bodies.length; i++) {
for (let j = 0; j < bodies.length; j++) {
if (i !== j) {
let force = calculateGravitationalForce(bodies[i], bodies[j]);
bodies[i].applyForce(force);
}
}
}
// Update and display bodies
for (let i = 0; i < bodies.length; i++) {
bodies[i].update();
bodies[i].display();
}
}
// Function to calculate gravitational force between two bodies
function calculateGravitationalForce(body1, body2) {
const distance = body1.position.dist(body2.position);
const magnitude = (G * body1.mass * body2.mass) / (distance * distance);
const force = p5.Vector.sub(body2.position, body1.position);
force.setMag(magnitude);
return force;
}
// Create the p5.js sketch