xxxxxxxxxx
93
let b;
let s;
let clicked = false;
function setup() {
createCanvas(640, 480);
b = new Bob(width / 2 + 150, 100);
s = new Spring(width / 2, 0, 140);
}
function draw() {
background(255);
s.connect(b);
s.display(b);
b.gravity();
b.checkClicked();
b.update();
b.display();
}
function Bob(x, y) {
this.loc = createVector(x, y);
this.vel = createVector(0, 0);
this.acc = createVector(0, 0);
this.mass = 10.0;
this.update = function() {
this.vel.add(this.acc);
this.loc.add(this.vel);
this.acc.mult(0);
};
this.display = function() {
stroke(0);
strokeWeight(2);
if (!clicked) {
fill(175);
} else {
fill(75);
}
ellipse(this.loc.x, this.loc.y, this.mass * 4, this.mass * 4);
};
this.applyForce = function(force) {
let f = force.copy();
f.div(this.mass);
this.acc.add(f);
};
this.checkClicked = function() {
// doesn't work with translate
let mouse = createVector(mouseX, mouseY);
let d = p5.Vector.dist(this.loc, mouse);
if (d < this.mass * 2 && mouseIsPressed) {
this.loc = mouse.copy();
this.vel = createVector(0, 0);
this.acc = createVector(0, 0);
clicked = true;
} else {
clicked = false;
}
};
this.gravity = function() {
let grav = createVector(0, this.mass / 10);
this.applyForce(grav);
};
}
function Spring(x, y, l) {
this.anchor = createVector(x, y)
this.len = l;
this.k = 0.1;
this.connect = function(b) {
let force = p5.Vector.sub(b.loc, this.anchor);
let d = force.mag();
let stretch = d - this.len;
force.normalize();
force.mult(-1 * this.k * stretch);
b.applyForce(force);
}
this.display = function(b) {
fill(100);
rectMode(CENTER);
rect(this.anchor.x, this.anchor.y, 10, 10);
stroke(0);
line(b.loc.x, b.loc.y, this.anchor.x, this.anchor.y);
}
}