Help with random() - Am I Going Crazy Here?

I'm trying to create a variable that is a random value between 0 and the width of the sketch with the following code:

void setup(){
  size(640, 480);
}

int x = int(random(0, width));

void draw(){
  println(x);
}

However the random value only ever returns 0?!?! Surely it should return a value between 0 and 640?!?!

Please help. I think I'm going crazy. :((

Answers

  • _vk_vk
    edited October 2013

    As you declared x inside setup() it is local, can't be accessed from draw() Either do the println() inside setup() or declare x a global var.

    //global var
    int x;
    
    void setup() {
      size(640, 480);
      x = int(random(width));// init.
        noLoop();
    }
    
    void draw() { 
      println(x);
    
    }
    
    //click to get a new number
    void mousePressed(){
      x = int(random(width));// init.
      redraw();
    }
    

    side note to format code in the forum ident lines 4 spaces, or select code and hit 'C' button.

  • it's not really a scope thing - because it's defined outside of the methods it gets run before setup() and that means that width isn't yet set to its proper value. hence the 0.

  • _vk_vk
    edited October 2013

    ops :) as the code was not formatted and the unusual placing of a global var I thought the declaration was inside setup... Anyway I was wrong, cause, was this the case, it would throw an error instead of printing 0. Thanks for pointing, sorry for misleading answer.

  • oh, also, tom, because you only set the value once that line in the draw will just print the same value over and over again. _vk's code fixes that by re-setting it in the mousePressed() method. or you can just move line 6 into the draw() loop to get it to change every single frame (and generate tons of output)

Sign In or Register to comment.