// Gravitational Attraction // The Nature of Code // The Coding Train / Daniel Shiffman // https://youtu.be/EpgB3cNhKPM // https://thecodingtrain.com/learning/nature-of-code/2.5-gravitational-attraction.html // https://editor.p5js.org/codingtrain/sketches/MkLraatd class Mover { constructor(mass, color_value) { this.pos = createVector(Math.random() * width, Math.random()*height); this.maxSpeed = 10; this.vel = createVector(0, 0); this.acc = createVector(0, 0); this.mass = mass; this.r = sqrt(this.mass) * 1; this.col = color(color_value); } mouse_mass() { if (focused) { let force = p5.Vector.sub(createVector(mouseX, mouseY), this.pos); let distanceSq = constrain(force.magSq(), 10, 1000); let G = 3; let strength = (G * this.mass * 10) / distanceSq; force.setMag(strength); this.applyForce(force); noStroke(); fill(100, 255, 100, 100); ellipse(mouseX, mouseY, 30); } } attract(other) { let force = p5.Vector.sub(this.pos, other.pos); let distanceSq = constrain(force.magSq(), 10, 1000); let G = 3; let strength = (G * this.mass * other.mass) / distanceSq; force.setMag(strength); other.applyForce(force); } applyForce(force) { let f = p5.Vector.div(force, this.mass); this.acc.add(f); } edges() { if (this.pos.y >= height - this.r) { this.pos.y = height - this.r; this.vel.y *= -1; } else if (this.pos.y <= this.r) { this.pos.y = this.r; this.vel.y *= -1; } if (this.pos.x >= width - this.r) { this.pos.x = width - this.r; this.vel.x *= -1; } else if (this.pos.x <= this.r) { this.pos.x = this.r; this.vel.x *= -1; } } update() { this.vel.add(this.acc); this.vel.limit(this.maxSpeed); this.pos.add(this.vel); this.acc.set(0, 0); } show() { noStroke(); fill(this.col); ellipse(this.pos.x, this.pos.y, this.r * 2); } }