I need help reversing the function

Hello, I am trying to get the background to fade to 255 and than when it hits 255 it fades back to 0. Please Help.

int bw = 0;
int bw_ = 1;

void setup() {
  size(300, 150);
}

void draw() {
  background(bw);
  bw = bw + bw_;
  if (bw > 255) bw = bw - bw_;
  println(bw);
}

Answers

  • edited March 2015
    // forum.processing.org/two/discussion/9879/
    // i-need-help-reversing-the-function
    
    color bg;
    int step = 2;
    
    void draw() {
      if ((bg += step) > 255 | bg < 0)  bg += step *= -1;
      background(bg);
      frame.setTitle("" + bg);
    }
    
  • int direction=1,current=0;
    void draw() {
    background(current);
    if(current==0)
    direction=1;
    else if(current==255)
    direction=-1;
    current+=direction;
    }
    
  • Another way to look at this question would be: "How could I draw a triangle wave?". I like this way cause it does not need "ifs". Some thing like this would do.

    triangleWave = maxNumber - abs(incrementedVar % (2*maxNumber) - maxNumber);

    Cool, isn't it?

    I have this old code using this, it's not drawing the wave, but using it for size and fill color. Also there is a sine wave for comparision. Check it out:

    float zigZag, toIncrement, speed =1, maxNumber = 255;
    float sine, x = 270, speed2 = 1;
    
    void setup() {
      size(800, 400);
      background(255);
    }
    void draw() {
      background(255);
    
      //triangle wave
      toIncrement+=speed;
      zigZag = maxNumber - abs(toIncrement % (2*maxNumber) - maxNumber);
      fill(zigZag);
      noStroke();
      ellipse( 150, height/2+100, 50, 50);
      strokeWeight(zigZag);
      stroke(0);
      line(100, height/2-100, 200, height/2-100);
      text("triangle = " + int(zigZag), 100, height-30);
      println("triangle wave value = " + zigZag);
    
    
      //sine wave
      x+=speed2;
      sine = (1+sin(radians(x)))*(maxNumber/2);
      fill(sine);
      noStroke();
      ellipse( 650, height/2+100, 50, 50);
      strokeWeight(sine);
      stroke(0);
      line(600, height/2-100, 700, height/2-100);
      fill(80);
      text("sine = " + int(sine), 600, height-30);
    }
    
Sign In or Register to comment.