xxxxxxxxxx
72
let self;
let attractor;
const G = 0.5; // Gravitational constant
function setup() {
createCanvas(400, 400);
// Initialize the objects
self = new Object(200, 200, 2, createVector(0, 0));
attractor = new Object(200, 100, 10, createVector(0, 0));
}
function draw() {
background(220);
// Update positions and calculate gravitational forces
self.update();
self.calculateGravitationalForce(attractor);
// Apply forces and update velocities
self.applyForce();
// Draw objects
self.display();
attractor.display();
}
class Object {
constructor(x, y, mass, velocity) {
this.position = createVector(x, y);
this.mass = mass;
this.velocity = velocity;
this.acceleration = createVector(0, 0);
}
update() {
// Update position based on velocity
this.position.add(this.velocity);
}
calculateGravitationalForce(attractor) {
// Calculate distance between objects
const distance = p5.Vector.dist(attractor.position, this.position);
// Calculate gravitational force
const forceMagnitude = ((this.position.mag() - attractor.position.mag()) / distance) * G * attractor.mass;
// Calculate the direction of the force
const forceDirection = p5.Vector.sub(attractor.position, this.position).normalize();
// Calculate the force vector
const force = forceDirection.mult(forceMagnitude);
// Apply the force to the object's acceleration
this.acceleration.add(force);
}
applyForce() {
// Update velocity based on acceleration
this.velocity.add(this.acceleration);
// Reset acceleration
this.acceleration.mult(0);
}
display() {
// Draw the object
fill(0);
ellipse(this.position.x, this.position.y, this.mass * 2);
}
}