Variable must change from 3.67 to 3.15

Hi there!

I need my variable i to go from 3.67 to 3.15 to 3.67 to 3.15 to 3.67 and so on. I’m able to do this just fine from 3.67 to 3.15, however I can’t manage to let it go back to 3.67. This is the code i’m using right now:

  if (i > 3.16) {
    i = i / 1.001
  }
  
  if(i > 3.67) {
    i = i * 1.001
  }

I understand why it’s not working, but I dont know how to fix it. :confused:
pls help

1 Like

You can use this:

n = 0.52 - abs(frameCount*0.1 % (2*0.52) - 0.52) + 3.15;

Eh? It’s a function to generate a triangle wave between 0 and 0.52 (the spread of your numbers) with a fixed offset of 3.15; it uses frameCount for the time variable; multiplying this by *0.1 slows down the speed of oscillation to a reasonable amount.

Alternatively,
n = 3.67 - abs(frameCount*0.1 % (2*0.52) - 0.52);

3 Likes

Thank you so much!
Clear explanation!

If you were trying to this with only introductory primitives (no modulo, no abs()) another way of expressing this idea in code is to set a step value and flip the sign on the step. This is the way that many bouncing ball implementations work

https://processing.org/examples/bounce.html

…only you are bouncing one variable along a single line, rather than in two dimensions x,y.

float step = 0.03;  // or 0.003415 etc
float max = 3.67;
float min = 3.16;
float i = (min+max)/2.0;

void setup() {
  frameRate(4);
}
void draw() {
  i += step;    // move
  if(i>max) {  // high bounce
    i=max;
    step = step * -1;
    println("ping");
  }
  if(i<min) {  // low bounce
    i=min;
    step = step * -1;
    println("pong");
  }
  println(step, i);  // status
}
3 Likes