xxxxxxxxxx
// engineer: j William Dunn
// 2024.0830
// Even if they separate for a while to explore,
// they are always drawn to one other and
// eventually reunite.
let particle1, particle2;
function setup() {
createCanvas(windowWidth,windowHeight);
particle1 = new Particle(windowWidth/2-100,height/2, 0);
particle2 = new Particle(windowWidth/2+100,height/2, 1);
noStroke();
}
function draw() {
background(0,10);
// Update and display particles
particle1.update();
particle1.show();
particle2.update();
particle2.show();
// Apply attraction
applyAttraction(particle1, particle2);
}
function windowResized() {
resizeCanvas(windowWidth,windowHeight);
}
function applyAttraction(p1, p2) {
let force = p5.Vector.sub(p2.position, p1.position); // Get the direction vector
let distance = force.mag(); // Magnitude of the distance
// Normalize and scale the force
if (distance > 0) {
force.normalize(); // Normalize to get the direction
force.mult(0.5 / distance); // Scale it based on distance (inverse square law)
}
if(force.mag()>1)force.setMag(1);
p1.velocity.add(force); // Apply the attraction force to particle 1
p2.velocity.sub(force); // Apply the opposite force to particle 2
}
class Particle {
constructor(x,y, id) {
this.position = createVector(x,y);
this.velocity = createVector(0,0);
this.size = 8;
this.id = id;
}
update() {
// Simulate Brownian movement
let randomForce = createVector(random(-0.1,0.1), random(-0.1,0.1));
this.velocity.add(randomForce);
// Update position
this.position.add(this.velocity);
// Stay within the canvas
this.position.x = constrain(this.position.x, 0, width);
this.position.y = constrain(this.position.y, 0, height);
// Dampen the velocity to simulate friction
this.velocity.mult(0.99);
}
show() {
if(this.id==0) fill(140,0,0); else fill(0,0,255);
ellipse(this.position.x,this.position.y, this.size);
}
}