xxxxxxxxxx
103
let m, a;
let c;
let force;
function setup() {
createCanvas(900, 500);
c = color(200, 200, 170);
m = new Mover(0, 400, 140, c);
a = new Attractor(width / 2, height / 2, 80);
force = createVector(0, 0, 1);
}
function draw() {
background(255, 155, 255);
m.log(20, 450);
const f = a.attract(m);
m.applyForce(f);
m.update();
m.display();
a.display();
}
class Mover {
constructor(x, y, m, c) {
this.pos = createVector(x, y, 1);
this.mass = m;
this.vel = createVector(0, 0);
this.acc = createVector(0, 0);
this.col = c || color(0, 150);
this.lastAcc = createVector(0, 0);
}
applyForce(force) {
// a copy so force vector is not changed and can be further used in other instances
const f = force.copy();
f.div(this.mass);
this.acc.add(f);
const frA = p5.Vector.mult(this.acc, -1);
frA.setMag(0.001);
// this.acc.add(frA);
}
update() {
const fr = p5.Vector.mult(this.vel, -1);
fr.setMag(0.02);
this.acc.add(fr);
this.vel.add(this.acc);
this.vel.add(this.fr);
this.pos.add(this.vel);
this.lastAcc.set(this.acc);
//clear acc each frame
this.acc.mult(0);
}
display() {
push();
fill(110);
noStroke();
circle(this.pos.x, this.pos.y, this.mass);
pop();
}
log(x, y) {
const data = `pos= .x_${nf(this.pos.x, 0, 2)}, .y_${nf(
this.pos.y,
0,
2
)}\nvel= .x_${nf(this.vel.x, 0, 2)}, .y_${nf(
this.vel.y,
0,
2
)}\nacc= .x_${nf(this.lastAcc.x, 0, 2)}, .y_${nf(this.lastAcc.y, 0, 2)}\n`;
textSize(17);
text(data, x, y);
this.lastAcc.mult(0);
}
} // <== eof mover class
class Attractor {
constructor(x, y, m, c) {
this.pos = createVector(x, y, 1);
this.mass = m;
}
attract(mover) {
let force = p5.Vector.sub(this.pos, mover.pos);
const dist = force.mag();
const strength = dist / 10;
force.setMag(strength);
return force;
}
display() {
push();
fill(110, 50, 60);
noStroke();
circle(this.pos.x, this.pos.y, this.mass);
pop();
}
} //<== eof attractor