mirror of
https://gitlab.com/MisterBiggs/Resume.git
synced 2025-06-16 01:16:39 +00:00
63 lines
1.6 KiB
JavaScript
63 lines
1.6 KiB
JavaScript
// 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(x, y, vx, vy, m) {
|
|
this.pos = createVector(x, y);
|
|
this.maxSpeed = 10;
|
|
this.vel = createVector(vx, vy);
|
|
this.acc = createVector(0, 0);
|
|
this.mass = m;
|
|
this.r = sqrt(this.mass) * 0.75;
|
|
this.col = color(255);
|
|
}
|
|
|
|
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);
|
|
}
|
|
} |