Unexpected conditional behavior in sin() calculation

Hey everyone! Entirely new to the forum and to Processing. I do have some casual knowledge of C# via Unity and coding in general but still very much a beginner.

I’ve been playing around with an example from the Processing reference guide and ran into some behavior that doesn’t make sense to me. My code is below:

float svar = 0;


void setup() {
  size(500, 500);
  background(155, 255, 200);
  frameRate(60);
}

void draw() {
  float a = 0.0;
  float inc = TWO_PI/25;

  if (mousePressed && (mouseButton == LEFT)) {
    svar += 5;
  } else if (mousePressed && (mouseButton == RIGHT)) {
    svar -= 5;
  } 

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

  loop();

  println(svar);

  if (mousePressed == true) {
    print("mouse pressed! ");
  }
}

The “svar” variable is not working the way I expected.

When I hit the Left mouse button the bottom half of the sine wave goes down, whereas I expected both sides of the wave to increase in amplitude. The Right mouse button lifts the top half up instead of decreasing the overall amplitude.

When I manually enter the value for “svar” the overall amplitude increases (both sides of the wave get longer), which is what I want. But making that value interactive does something entirely different.

Another thing that’s confusing me is the more I’ve pressed either button the more of a delay there is before anything happens.

Any help with this would be appreciated.

Hello,

Add background(255); to draw() and see what happens.

Reference:
https://processing.org/reference/background_.html

:)

1 Like

Not entirely sure what happens when I do that but does it have to do with background() being “typically used within draw() to clear the display window at the beginning of each frame”? And the rest is just my math is wrong.

I’ve got it working the way I want using line(i, 100, i, 100+(svar/10*sin(a))*45) and placing background() in draw() instead of setup.

Thank you!

1 Like

Be careful of the priority of operators when using math formula.

When you write 100+sin(a)*40+svar, what you do is first 40 * sin(a) then you add 100 then you add svar. So you are never changing the magnitude of your sin.

Instead you want 100 + (40 + svar) * sin(a)
Also we tend to put the multiplier before sin for readability.

Simply doing this and adding background(155, 255, 200); at the beginning of your draw loop and it is working.

2 Likes