Random not working

im trying to get a ball to spawn on one of three heights: 100, 200 and 300. i set the random to produce a number from 1 to 3. when the outcome is 1 the height is 100, when it’s 2 the height is 200 and when it’s 3 the height is 300. somehow the outcome is always 0 and the ball spawns on height 300. i also tried to use a string for the random to select the number from, didn’t work either.

void setup() {
  size(600,400) ;
  background(10, 80, 100);
}
int ballX = 300;
float ballY2 = random(1,3); 
int ballY;

void draw() {
  background(10, 80, 100);

  noStroke();
  fill(229,79,79);
  ellipse(ballX,ballY,50,50);
  
  if (ballY2 <1); {
    ballY = 102;
} if (ballY2 <2); {
    ballY = 202;
} if (ballY2 <3); {
    ballY = 302;
  }
}{
print (ballY2);}

In your if statements, ballY2 < 3 will always be true because of the way you set it up. Any random number you generate using random(1,3) will be less than 3, and will make ballY = 302;

An alternative approach would be to define your height choices into an array, and make the random() generate the random index instead. random(3) will generate any float number between 0 and 3, so using floor would round down to one of three options: 0, 1, 2.

int ballX = 300;
int[] heightOptions = {100,200,300};
int ballY = heightOptions[floor(random(3))];

This is more readable and less error prone, and enables you to define more options easily instead of writing multiple ifs.

1 Like

ballY2 = (int) random(1, 4) * 100 + 2;

Thanks, helped a lot!