Random 'if'

edited February 2017 in Questions about Code

Hi

I'm very new to processing and I'm having trouble using random. I want 'if' to react when the difference between TimeMeasurement and millis is a random number between 2000 and 10000. How do I do this?

The program runs when I type e.g. "if (difference > 5000)", but not when I use random.

Can you help?

int TimeMeasurement = 0; 

void setup() {
 size(800,600);
}

void draw() {
  background(255);
  fill(255, 0, 0);
  ellipse(400, 300, 20, 20);

  int difference = millis() - TimeMeasurement; 
  println(millis() + " - " + TimeMeasurement); 

  if (difference = random(2000, 10000)) { // this is not working - why? 
    background(255);
    fill(93, 224, 102);
    ellipse(400, 300, 300, 300);
  }
}

void keyPressed() { // 
  TimeMeasurement = millis(); 
}
Tagged:

Answers

  • to compare things in if you have to use 2 equal signs, so " if(difference == random(2000, 10000) Also, it wont work because random(2000,10000) will output a number like 4324 for example, there's pretty slim chance it will be the same as difference. I think what you want is if(difference >=2000 && difference <=10000) to check if difference is between 2000 and 10000.

  • edited February 2017

    @skaarup91 --

    You probably do not want to assign your random number in your if check. That will generate a different random() number every single frame -- e.g. 60 times a second -- and greatly increases the likelihood that a short time will trigger the event.

    Instead, assign a variable from random() once in setup, and then update your variable with random() again inside the if statement. This will pick a time, never update it until it triggers, then update it once more only after it has been triggered. That's probably what you want.

Sign In or Register to comment.