Is it possible to create a pendolum with sin() and cos() ?

edited April 2016 in Questions about Code

I am currently trying to create an animated pendolum, but i fail with defining the right y-axis motion. Is there a special trick?

float a;

float diameter;
float posx;
float posy;

void setup() {
  size(300, 300); 
  strokeWeight(1);
}  

void draw() {

  diameter = width/2-60;

  posx = sin(diameter+a)*diameter;  

  posy = cos(diameter+a)*diameter+width/2;  


// Draw the pendolum

  translate(width/2, height/2);

  // The ellipse in the center 
  ellipse(0, 0, 40, 40);

  // The lace  
  line(0, 0, posx, posy);

  // the pendolum
  ellipse(posx, posy, 20, 20);

  a = a + PI*2/250;
}

Answers

  • Line 16 can be moved into setup () since it needs only to be calculated once.

    It would be usual to add a background statement at the start of the draw method to clear the frame before drawing the new pendulum position.

    You formulae on lines 16 and 18 make no sense because
    sin and cos are used on angles and are not related to the diameter
    the y position is not related to the width of the sketch but you use it in line 18

    Change the formulae to

    posx = sin(a)*diameter;  
    posy = cos(a)*diameter;
    

    Line 23 moves the pendulum axis to the centre of the screen. For realistic pendulum movement the anagle a should swing between 80 and 100 degrees, since the down direction is 90 degrees.

  • Thank you very much quark! I understand everything instead of the last sentence:

    What do you mean with "For realistic pendulum movement the anagle a should swing between 80 and 100 degrees, since the down direction is 90 degrees."?

    Shall i change a?

  • Answer ✓

    In computer graphics

    East is zero degrees
    South is 90 degrees
    West is 180 degrees
    North is 270 degrees

    So if a equals 80 degrees it is just right of south and if 100 degrees just left of south. So you need to create code where a goes

    80 -> 100 -> 80 -> 100 and so on. Obviously in the sketch a would have to be in radians.

  • Great! Thanks!

  • edited April 2016

    Thank you guys! I've found the perfect solution:

    float a;
    
    // Length of the string
    float cord = 100;
    
    float posx;
    
    float posy;
    
    color black = #222222;
    color white = #eeeeee;
    color red = #E14C45;
    
    void setup() {
      size(300, 300); 
      stroke(black);
    }  
    
    void draw() {
      background(white); 
      fill(red);
      posx = sin(HALF_PI*sin(a))*cord;  
      posy = cos(HALF_PI*sin(a))*cord;
    
    
    
      translate(width/2, height/2);
      line(0, 0, posx, posy);
      ellipse(posx, posy, 10, 10);
    
      ellipse(0, 0, 40, 40);
    
      noFill();
    
      ellipse(0, 0, 200, 200);
    
      // a is the angle that 
    
      a = a + PI/100; 
    
      println(a);
    }
    
Sign In or Register to comment.