sketch
//f spring = -k*x
//f = ma
//m= -k
//a = x
float y = 250;
int restLength = 2;
//PVector velocity = new PVector(0,0);;
PVector force = new PVector(0,0);
float x = 0.0;
Particle bob = new Particle(350,300);
Particle anchor = new Particle(300,0);
Spring spring = new Spring(0.01,200,bob,anchor);
PVector gravity = new PVector(0,0.02);
PVector v = new PVector(0,0);
//spring constant
float k = 0.01;
float damping = 0.5;
float spacing = 10;
ArrayList<Particle>particles = new ArrayList<Particle>();
ArrayList<Spring>springs = new ArrayList<Spring>();
int particlesNum = 20;
void setup(){
size(600,400);
for(int i=0;i<particlesNum;i++){
particles.add(new Particle(200,i*spacing));
//particles.get(i).locked = true;
if(i!=0){
Particle a = particles.get(i);
Particle b = particles.get(i-1);
Spring spring = new Spring(k,spacing,a,b);
springs.add(spring);
}
}
particles.get(0).locked = true;
};
void draw(){
background(112,50,126);
for(Spring s: springs){
s.update();
//s.show();
}
Particle tail = particles.get(particles.size()-1);
Particle head = particles.get(0);
beginShape();
noFill();
curveVertex(head.pos.x,head.pos.y);
for(Particle p: particles){
p.applyForce(gravity);
p.update();
//p.show();
curveVertex(p.pos.x,p.pos.y);
}
curveVertex(tail.pos.x,tail.pos.y);
endShape();
if(mousePressed){
tail.pos.set(mouseX,mouseY);
tail.vel.set(0,0);
}
};
spring
class Spring{
float k,restLength;
Particle a,b;
Spring(float k,float rl,Particle a,Particle b){
this.k = k;
restLength = rl;
this.a = a;
this.b = b;
};
void update(){
PVector force = PVector.sub(b.pos,a.pos);
float x = force.mag()-restLength;
force.normalize();
force.mult(k*x);
a.applyForce(force);
force.mult(-1);
b.applyForce(force);
};
void show(){
strokeWeight(4);
stroke(255);
//line(a.pos.x,a.pos.y,b.pos.x,b.pos.y);
};
};
particle
class Particle{
PVector acc,vel,pos;
float mass = 1.0,damp = 0.99;
boolean locked = false;
Particle(PVector pos){
this.acc = new PVector(0,0,0);
this.vel = new PVector(0,0,0);
this.pos = pos.copy();
};
Particle(float x,float y){
this.acc = new PVector(0,0,0);
this.vel = new PVector(0,0,0);
this.pos = new PVector(x,y);
};
void run(){
this.update();
this.show();
};
void applyForce(PVector force){
PVector f = force.copy();
f.div(this.mass);
acc.add(f);
}
void update(){
if(!locked){
vel.mult(damp);
vel.add(acc);
pos.add(vel);
acc.mult(0);
}
};
void show(){
stroke(200);
strokeWeight(2);
fill(127);
ellipse(pos.x,pos.y,10,10);
};
};
output