class Spring { Ball b1, b2; float rest; // rest length float k; // spring constant // Initialize a Spring between balls b1 and b2, with spring constant k Spring(Ball b1, Ball b2, float k) { this.b1 = b1; this.b2 = b2; this.k = k; rest = dist(b1.x,b1.y, b2.x,b2.y); } void draw() { line(b1.x,b1.y, b2.x,b2.y); } // Apply the spring to its masses void apply() { // Restorative force is proportional to difference in length from rest length float len = dist(b1.x,b1.y, b2.x,b2.y); if (len>0) { float f = k*(len-rest); // Apply it to x coordinates, moving each toward the other float fx = f*(b1.x-b2.x)/len; b1.vx -= fx; b2.vx += fx; // Similarly with y float fy = f*(b1.y-b2.y)/len; b1.vy -= fy; b2.vy += fy; } } }