Trouble using random.

edited November 2014 in Programming Questions

Hello, I've been having the following issue while using the random command:

Whenever it's inside void draw, it sorts a different value every time, but if it's outside, a value is sorted out and it's repeated until the window is closed.

I know that is a property of it, but in order for the program to work as it's intended the random value has to affect all the other voids, beyond just void draw. Anyone got a clue on this?

Just a recap, I need a way to make the random command give me a new value each time, but without being restricted only to void draw.

Thanks in antecipation, Krieger.

Tagged:

Answers

  • code outside functions will run once

    code inside setup will run once

    code inside draw() runs on every frame

    float every;
    float once;
    
    void setup() {
        once = random(100);
    }
    
    void draw() {
        float local = random(100);
        every = random(100);
        println(once + " : " + every);
    }
    

    'every' is different every time - it's changed in draw(), every frame.

    'once' is set once and will not change until you change it.

    'every' and 'once' are globals and will be available anywhere in your code. 'local' can only be used within draw(). it's good practice to limit variables to the correct scope - don't use global variables when local ones will do.

Sign In or Register to comment.