Create a Sin wave line with Processing

user288093 picture user288093 · Mar 7, 2010 · Viewed 11k times · Source

first post here, and probably an easy one.

I've got the code from Processing's reference site:

float a = 0.0;
float inc = TWO_PI/25.0;

for(int i=0; i<100; i=i+4) {
  line(i, 50, i, 50+sin(a)*40.0);
  a = a + inc;
}

http://processing.org/reference/sin_.html

However, what I need is a line that follows the curve of a Sin wave, not lines representing points along the curve and ending at the 0 axis. So basically I need to draw an "S" shape with a sin wave equation.

Can someone run me through how to do this?

Thank you in advance, -Askee

Answer

kennytm picture kennytm · Mar 7, 2010

To draw a curve you need to store the previous point's position.

float a = 0.0;
float inc = TWO_PI/25.0;
float prev_x = 0, prev_y = 50, x, y;

for(int i=0; i<100; i=i+4) {
  x = i;
  y = 50 + sin(a) * 40.0;
  line(prev_x, prev_y, x, y);
  prev_x = x;
  prev_y = y;
  a = a + inc;
}