Value will not go negative (move and bounce)

I’ve used almost exact code before but its not working this time. Any idea why?

float obstacleX;
float obstacleMoveX;

square(obstacleX, obstacleY, 80);
obstacleMoveX = 2;
obstacleX = obstacleX + obstacleMoveX;
if (obstacleX >= 50) {
  obstacleMoveX = -obstacleMoveX;
}

Is it because you keep re-initializing obstacleMoveX to 2 every time draw() gets called? Move that initialization either into setup() or just to the global scope.

1 Like

Example

float obstacleX = 2;
float obstacleY = 102;

float obstacleMoveX = 2;

// --------------------------------------------------------------

void setup() {
  size(1900, 1000);
}

void draw() {
  background(0);

  square(obstacleX, obstacleY, 80);

  obstacleX += obstacleMoveX;

  if (obstacleX >= 500) {
    obstacleMoveX = -obstacleMoveX; // reverse
  }
}

2 Likes

Thank you so much! This helped a lot!

1 Like