Example
// Learning Processing
// Daniel Shiffman
// http://www.learningprocessing.com

// Example 13-6: Oscillation

float theta = 0.0;

void setup() {
  size(200,200);
  smooth();
}


void draw() {
  background(255);
  
  // The output of the sin() function oscillates smoothly between -1 and 1. 
  // By adding 1 we get values between 0 and 2. 
  // By multiplying by 100, we get values between 0 and 200 which can be used as the ellipse's x location.
  float x = (sin(theta) + 1) * width/2; 
  
  // We can also use Processing's "map()" function to achieve the same results
  // http://processing.org/reference/map_.html
  // float x = map(sin(theta),-1,1,0,width);

  // With each cycle, increment theta
  theta += 0.05;
  
  // Draw the ellipse at the value produced by sine
  fill(0);
  stroke(0);
  line(width/2,0,x,height/2);
  ellipse(x,height/2,16,16);
}
  • Dave

    the code says

    // The output of the sin() function oscillates smoothly between 1 and 1.

    should this not say:

    // The output of the sin() function oscillates smoothly between -1 and 1.

    confused me a bit.

  • MD

    I noticed a small quirk with this statement,
    float x = (sin(theta) + 1) * width/2;

    When \width/2\ is replaced by a variable \float r = width/2\, the ellipse doesn’t oscillate. Does anyone know why?

  • http://www.learningprocessing.com Daniel Shiffman

    You must have a parentheses out of place or something, this works no problem:

      float r = width/2;
      float x = (sin(theta) + 1) * r;
    

    Also, if you declared r above setup() then widht won’t have been set yet and the value would be 0.

  • http://www.learningprocessing.com Daniel Shiffman

    @Dave, whoops yes, that is an error will fix now!