xxxxxxxxxx
102
// The Nature of Code
// Daniel Shiffman
// http://natureofcode.com
// A soft pendulum (series of connected springs)
class Chain {
constructor(l, n, r, s, x, y) {
// This list is redundant since we can ask for physics.particles, but in case we have many of these
// it's a convenient to keep track of our own list
this.particles = [];
// Chain properties
this.totalLength = l; // How long
this.numPoints = n; // How many points
this.radius = r; // Strength of springs
this.strength = s; // Radius of ball at tail
var len = this.totalLength / this.numPoints;
// Here is the real work, go through and add particles to the chain itself
for (var i = 0; i < this.numPoints; i++) {
// Make a new particle with an initial starting location
var particle = new Particle(x+i*len, y);
// Redundancy, we put the particles both in physics and in our own ArrayList
physics.addParticle(particle);
this.particles.push(particle);
// Connect the particles with a Spring (except for the head)
if (i != 0) {
var previous = this.particles[i - 1];
var spring = new VerletSpring2D(particle, previous, len, this.strength);
// Add the spring to the physics world
physics.addSpring(spring);
}
}
// Keep the top fixed
// var head = this.particles[0];
// head.lock();
// Let's keep an extra reference to the tail particle
// This is just the last particle in the ArrayList
this.tail = this.particles[this.numPoints - 1];
this.head = this.particles[0];
this.head.lock();
this.head.radius = this.radius;
this.tail.radius = this.radius;
// Some variables for mouse dragging
this.offset = createVector();
this.dragged = false;
}
// Check if a point is within the ball at the end of the chain
// If so, set dragged = true;
// contains(x, y) {
// var d = dist(x, y, this.head.x, this.head.y);
// if (d < this.radius) {
// this.offset.x = this.head.x - x;
// this.offset.y = this.head.y - y;
// this.head.lock();
// this.dragged = true;
// }
// }
// Release the ball
// release() {
// this.head.lock();
// this.dragged = false;
// }
// Update tail location if being dragged
updateTail(x, y) {
this.tail.set(x + this.offset.x, y + this.offset.y);
}
updateHead(x, y) {
//if (this.dragged) {
this.head.set(x + this.offset.x, y + this.offset.y);
//}
}
isAbove(){
}
// Draw the chain
display() {
// Draw line connecting all points
beginShape();
stroke(200);
strokeWeight(2);
noFill();
for (var i = 0; i < this.particles.length; i++) {
vertex(this.particles[i].x, this.particles[i].y);
}
endShape();
this.tail.displayTail();
// this.head.displayHead();
}
}