xxxxxxxxxx
73
class Body {
constructor(x, y, r) {
this.r = r;
this.m = r ** 2;
this.pos = createVector(x, y);
this.vel = createVector(random(-1, 1), random(-1, 1));
this.acc = createVector(0, 0);
this.c = this.setColor();
this.isOut = false;
}
attract(other) {
if (this == other) {
return;
}
let force = p5.Vector.sub(this.pos, other.pos);
let disSq = force.magSq();
let strength = (G * (this.m * other.m)) / disSq;
force.setMag(strength);
other.applyForce(force);
}
applyForce(force) {
let f = p5.Vector.div(force, this.m);
this.acc.add(f);
if (this.vel.mag() > maxVel) {
this.vel.setMag(maxVel);
}
}
update() {
this.vel.add(this.acc);
this.pos.add(this.vel);
this.acc.set(0, 0);
this.out();
}
out() {
if (this.pos.x < 0) {
this.isOut = true;
} else if (this.pos.x > width) {
this.isOut = true;
} else if (this.pos.y < 0) {
this.isOut = true;
} else if (this.pos.y > height) {
this.isOut = true;
}
}
show() {
noStroke();
fill(255, random(15, 30));
ellipse(this.pos.x, this.pos.y, this.r * 2 + 11);
fill(255, random(30, 40));
ellipse(this.pos.x, this.pos.y, this.r * 2 + 5);
fill(this.c);
ellipse(this.pos.x, this.pos.y, this.r * 2);
}
setColor() {
let colors = [
color(244, 251, 210),
color(255, 253, 230),
color(245, 233, 180),
];
return colors[int(random(3))];
}
}