xxxxxxxxxx
100
class Bob {
constructor(attached, location, k) {
this.attached = attached;
this.location = location;
this.equilPos = this.location.copy();
this.k = k;
this.r = 10;
this.velocity = createVector(0, 0);
this.acceleration = createVector(0, 0);
}
stop() {
this.acceleration.mult(0);
this.velocity.mult(0);
// this.location.set(this.equilPos);
this.stopped = true;
}
applyForce(force) {
this.acceleration.add(force);
}
update() {
if (this.stopped) {
this.stopped = false;
return
}
this.applyForce(gravity)
if (p5.Vector.dist(this.location, this.equilPos) > 0) {
let force = this.location.copy();
force.sub(this.equilPos);
force.mult(-this.k);
this.applyForce(force);
}
this.acceleration.div(timestep);
this.velocity.add(this.acceleration);
this.velocity.mult(0.99999);
this.location.add(this.velocity);
}
show() {
strokeWeight(2);
stroke(0);
line(this.attached.x, this.attached.y, this.location.x, this.location.y);
fill(35, 60, 255);
circle(this.location.x, this.location.y, this.r);
}
}
let bob;
let timestep = 1000;
let setting = false
let gravity ;
let gravitySlider
function setup() {
createCanvas(400, 400);
bob = new Bob(createVector(200, 50), createVector(200, 200), 3e-5);
bob.location = createVector(200, 200);
let b = createButton("Stop");
b.mousePressed(() => {
bob.stop();
});
gravity = createVector(0, 0.001)
gravitySlider = createSlider(0, 0.01, 0.0001, 0.00001)
gravitySlider.input(() => {
gravity.set(0, gravitySlider.value())
})
}
function mousePressed() {
if (setting) return
if (mouseX >= 0 && mouseX < width && mouseY >= 0 && mouseY < height) {
bob.location.set(mouseX, mouseY);
setting = true
}
}
function mouseReleased() {
setting = false
}
function draw() {
background(220);
for (let i = 0; i < timestep; i++) {
bob.update();
}
bob.show();
noStroke();
fill(255);
textSize(14);
text(bob.location, 10, 15);
text(bob.velocity, 10, 45);
text(bob.acceleration, 10, 70);
}