You need Internet Explorer and the .NET Framework installed in order to see the sketch.

built with PROCESSING.NET


Source Code:            Syntax: C#
// Spring
// by REAS <http://reas.com>

// Click, drag, and release the horizontal bar to start the spring.

// Updated 1 September 2001

// Modified for Processing.NET

// Spring drawing constants for top bar
int s_height = 16;     // Height
int left = 50;         // Left position
int right = 150;       // Right position
int max2 = 100;         // Maximum Y value // MODIFIED
int min2 = 20;          // Minimum Y value
bool over = false;  // If mouse over
bool move = false;  // If mouse down and over

// Spring simulation constants
double M = 0.8;   // Mass
double K = 0.2;   // Spring constant
double D = 0.92;  // Damping
double R = 60;    // Rest position

// Spring simulation variables
double ps = 60.0; // Position
double vs = 0.0;  // Velocity
double as2 = 0;    // Acceleration // MODIFIED
double f = 0;     // Force


public override void setup() 
{
  size(200, 200);
  rectMode(CORNERS);
  noStroke();
  framerate(60);
}

public override void draw() 
{
  background(102);
  updateSpring();
  ddrawSpring(); // MODIFIED
}

void ddrawSpring() // MODIFIED 
{
  // Draw base
  fill(0.2);
  double b_width = 0.5 * ps + -8;
  rect(width/2 - b_width, ps + s_height, width/2 + b_width, 150);

  // Set String and draw top bar
  if(over || move) { 
    fill(255);
  } else { 
    fill(204);
  }
  rect(left, ps, right, ps + s_height);
}


void updateSpring()
{
  // Update the spring position
  if(!move) {
    f = -K * (ps - R);    // f=-ky
    as2 = f / M;           // Set the acceleration, f=ma == a=f/m // MODIFIED
    vs = D * (vs + as2);   // Set the velocity // MODIFIED
    ps = ps + vs;         // Updated position
  }
  if(abs(vs) < 0.1) {
    vs = 0.0;
  }

  // Test if mouse is over the top bar
  if(mouseX > left && mouseX < right && mouseY > ps && mouseY < ps + s_height) {
    over = true;
  } else {
    over = false;
  }
  
  // Set and constrain the position of top bar
  if(move) {
    ps = mouseY - s_height/2;
    if (ps < min2) { ps = min2; } // MODIFIED
    if (ps > max2) { ps = max2; } // MODIFIED
  }
}

public override void mousePressed() {
  if(over) {
    move = true;
  }
}

public override void mouseReleased()
{
  move = false;
}