Simon
Simon

Reputation: 2002

How to make an increment followed by a decrement continuously?

I am trying to obtain an increment that goes up from 0 to n, then decreases from n-1 to 0, and repeats the cycle over and over.

In this example written in Processing, I would like the background to go from black(i=0) to white(i=255) incrementally then white to black incrementally and so forth. Now I only get it to go from black to white, and then it comes back to black suddenly.

int i = 0;

void setup(){
size(640, 360);
frameRate(60);
}
void draw(){
  background(i);
  i++;
  if(i==256){i=0;}
}

Upvotes: 0

Views: 229

Answers (2)

v.k.
v.k.

Reputation: 2854

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);

Coll, 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);
}

Upvotes: 1

James Anderson
James Anderson

Reputation: 27478

Try -

 int change = 1;
 void draw(){
  background(i);
  i = i + change;
  if(i==256){change = -1;}
  if(i==0){change = 1;}
}

Upvotes: 5

Related Questions