spring, oscillation and stuff...

edited February 2014 in Questions about Code

Hi all,
I have a question concerning physics in the most part.
I have modelled a spring after this funcrion (Hooke's Law): F = k * X
http://en.wikipedia.org/wiki/Hooke's_law
here is the code:

float force = 0;
float accel = 0;
float speed = 5;
float posMid = 300;
float pos = 300;
float x;
float mass = 1000;
float k = 1;
void setup(){
  size(600,600);
  frameRate(60);
}

void draw(){
  background(0);
  x = posMid - pos;
  force = k*x;
  accel = force / mass;
  speed += accel;
  pos += speed;
  stroke(255,0,0);
  line(300,pos,300,posMid);
  noStroke();
  fill(255);
  ellipse(300,pos,10,10);
}

any ideas on how to add friction to the system?,
so that the system slowly stops oscillating...

Answers

  • Answer ✓

    I dunno either! You gotta w8 for some1 w/ physics knowledge here! :(
    Here's my sorry attempt: :@)

    // forum.processing.org/two/discussion/2868/
    // spring-oscillation-and-stuff-
    
    float force, accel, speed = 5;
    float y, cx, cy;
    
    static final float K = 1, DIM = 10;
    static final float MASS = 1e3, FRICTION = .75;
    
    void setup() {
      size(600, 600);
      fill(-1);
    
      cx = width >> 1;
      y = cy = height >> 1;
    }
    
    void draw() {
      update();
      clear();
    
      stroke(#FF0000);
      line(cx, y, cx, cy);
    
      noStroke();
      ellipse(cx, y, DIM, DIM);
    }
    
    void update() {
      force = (cy - y) * K;
      accel = force / MASS * FRICTION;
    
      y += speed += accel;
    }
    
  • Friction is proportional to the velocity (sometimes as velocity squared, depending on the situation), so just subtract that from the force:

    float force = 0;
    float accel = 0;
    float speed = 5;
    float posMid = 300;
    float pos = 300;
    float x;
    float mass = 1000;
    float k = 1;
    float drag = 3;
    void setup() {
      size(600, 600);
      frameRate(60);
    }
    
    void draw() {
      background(0);
      x = posMid - pos;
      force = k*x - drag*speed;
      accel = force / mass;
      speed += accel;
      pos += speed;
      stroke(255, 0, 0);
      line(300, pos, 300, posMid);
      noStroke();
      fill(255);
      ellipse(300, pos, 10, 10);
    }
    
  • It's been a long time, I had forgotten about this thread. Thanks after all. :)

Sign In or Register to comment.