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 float k = 0.1; // spring constant float d = 0.95; // damping // Initialize a Spring at rest position (x0,y0) Spring(float x0, float y0) { cx = x0; cy = x0; x = x0; y = y0; } void draw() { // Set color from stretchiness float col = 128+128*dist(x,y, cx,cy)/max(width/2,height/2); fill(col); stroke(col); // Attach to wall line(width/2,0,x,y); line(width/2,height,x,y); ellipse(x,y,r*2,r*2); } void update() { if (mousePressed && dist(mouseX,mouseY,x,y) < r) { x = mouseX; y = mouseY; } else { // Spring equations for both x and y vx -= k * (x-cx); vx *= d; x += vx; vy -= k * (y-cy); vy *= d; y += vy; } } }