class BoxSpring { float cx, cy; // rest position float x, y; // current position float vy=0; // velocity (only spring up and down) float w, h; // width and height of the box float k; // spring constant float d; // damping // Initialize a Spring at rest position (x0,y0), of size w*h BoxSpring(float x0, float y0, float w, float h) { x = x0; y = y0; cx = x0; cy = y0; this.w = w; this.h = h; // Random spring constant and damping k = random(0.01,0.02); d = random(0.95,1.0); } void draw() { // Color according to how far away from rest position float r = abs(y-cy); fill(255,255-r,2*r); rect(x,y,w,h); } void update() { if (mouseX > x-w/2 && mouseX < x+w/2 && mouseY > y-h/2 && mouseY < y+h/2) { // Give it a kick of velocity when (while) mouse is over it vy = 10; } else { // Usual spring stuff vy -= k * (y-cy); vy *= d; y += vy; } } }