class Spring { float cx, cy; // rest position float x, y; // current position float vx=0, vy=0; // velocity in the two directions float r = 10; // radius color c=color(255); // color float k = 0.1; // spring constant float d = 0.95; // damping boolean grabbed=false; // whether I have been grabbed by the mouse // Initialize a Spring at rest position (x0,y0) Spring(float x0, float y0, color c0) { cx = x0; cy = x0; x = x0; y = y0; } void draw() { fill(c); stroke(red(c)/2,green(c)/2,blue(c)/2); line(cx,cy,x,y); ellipse(cx,cy,r,r); ellipse(x,y,r*2,r*2); if(grabbed) { fill(red(c)/2,green(c)/2,blue(c)/2); ellipse(x,y,r,r); } } void updateVelocity() { // Apply spring force vx -= k * (x-cx); vy -= k * (y-cy); // Damp vx *= d; vy *= d; } void updateGrabbed() { // if I am not grabbed yet, grab me if the mouse is clicked on me if(!grabbed) grabbed = mousePressed && dist(mouseX,mouseY,x,y) < r; // otherwise stop grabbing me when I release the mouse else grabbed = mousePressed; } void update() { // check if grabbed updateGrabbed(); // follow the mouse if grabbed if(grabbed) { x = mouseX; y = mouseY; vx = mouseX - pmouseX; vy = mouseY-pmouseY; } else { // obey physics otherwise // update the velocity updateVelocity(); // Move in the appropriate direction by the step size x += vx; y += vy; } } }