How to make a variable decrease then increase when it reaches a point

So I have my variable x and I want it to keep on decreasing until it reaches 10 and then start increasing to 50 then go back to 10 and keep on repeating (e.g. 12, 11, 10, 11, 12, 13, …, 49, 50, 49, 48, …, 11, 10).

This was my code:

    if x = 10:
        x = x + 1
    else:
        x = x - 1

But then I realised this wouldn’t work since x would just end up being 10, 11, 10, 11…, so now I’m not so sure what to do. Does anyone know what the easiest way I can do this is? Thank you very much :slight_smile:

You could have a 2nd variable which would store the value that x would use to increase or decrease.

And then invert its signal value when x reaches any of the minimum & maximum limits:

Python Mode:

MIN_X, MAX_X = 10, 50
x, incX = MIN_X, 1

def setup():
    frameRate(5)


def draw():
    global x, incX
    this.print(x, incX, TAB)
    x += incX
    if x == MIN_X or x == MAX_X: incX *= -1

Java Mode:

static final int MIN_X = 10, MAX_X = 50;
int x = MIN_X, incX = 1;

void setup() {
  frameRate(5);
}

void draw() {
  print(x, incX, TAB);
  x += incX;
  if (x == MIN_X || x == MAX_X)  incX *= -1;
}

p5.js Mode:

const MIN_X = 10, MAX_X = 50;
var x = MIN_X, incX = 1;

function setup() {
  frameRate(5);
}

function draw() {
  print(x, incX);
  x += incX;
  if (x == MIN_X || x == MAX_X)  incX *= -1;
}
4 Likes

I think the solution from @GoToLoop is brilliant, as usual, and even compares to Java mode and JavaScript (p5js) which can be very helpful for people using the other modes.

I’ve used his code but changed the variable names to something I would use myself in class, and tried some variations on the syntax, nothing essential changed, see if this helps:

MIN_X, MAX_X = 10, 50
x = MIN_X
direction = 1

def setup():
    frameRate(5)

def draw():
    global x, direction
    println("x:{} direction:{}".format(x, direction))
    x = x + direction  # same as x += direction
    if x == MIN_X or x == MAX_X:
        direction = -direction  # same as direction *= -1
2 Likes