Example
// Learning Processing
// Daniel Shiffman
// http://www.learningprocessing.com

// Example 4-7: Filling variables with random values

float r;
float g;
float b;
float a;

float diam;
float x;
float y;

void setup() {
  size(200,200);
  background(255);
  smooth();    
}

void draw() {
  // Each time through draw(), new random numbers are picked for a new ellipse.
  r = random(255);
  g = random(255);
  b = random(255);
  a = random(255);
  diam = random(20);
  x = random(width);
  y = random(height);
  
  // Use values to draw an ellipse
  noStroke();
  fill(r,g,b,a);
  ellipse(x,y,diam,diam);
}



  • haptiK

    When discussing the usage of the random() function in your book, you explained the need to sometimes change the value received from random() into an integer using int() or casting it as (int).

    Granted it is not necessary to always do this, but I think it would have been much wiser to do it in this example considering RGB values should really not be floats and doing so would have added a level of consistency.

  • http://www.learningprocessing.com Daniel Shiffman

    Thanks for the suggestion. Although color values (as well as pixel values) are truly integers at heart, Processing allows you to use floats with all of its functions for convenience. So I find that it’s actually often more confusing to have to write the extra code:

    int r;

    r = int(random(255));

    But this is an important point that I should be aware of, thank you!!

  • http://www.mimran.com Patrick Mimran

    I do not understand why i am obliged to declare two times the same variables x=0 X=0 y=0 Y1=0
    to make this work . If i only declare two variables and use them in all the ifs it does not work .
    i do not understand why , could you give to me a little explanation

    Thanks

    Patrick

    int x = 0 ;
    int y = 0 ;
    int X = 0 ;
    int Y1 = 0 ;
    int H = 30 ;
    int speed = 5 ;

    int state = 0 ;

    void setup() {
    size (500, 500);
    smooth();
    }

    void draw()

    {

    background(204);

    fill ( 250 , 0 , 0 );

    ellipse(x , y + 250 , 30 ,30 ) ;
    x = x + speed ;
    if ( x > width+30) {
    state = 1 ;
    }
    if (state == 1 ) {
    fill ( 200 , 30 , 89 );
    ellipse (width/2 ,y , 30 ,30 ) ;
    y = y + speed ;

    if ( y > height+30 ) {
    state = 2 ;
    }

    if ( state == 2 ) {

    ellipse ( X , height/2 , 30 ,H ) ;
    H += 3 ;
    X = X + speed ;
    if ( X > width + 30 )
    state = 3 ;

    }

    if ( state == 3 ) {
    fill ( 50 , 150 , 200 );
    ellipse (width/2 ,Y1 , 90 ,H ) ;
    H += 1 ;
    Y1 = Y1 + speed ;
    state = 4 ;

    } }}

  • Jonathan Dryhurst Roberts

    Patrick: variables x, and X are not the same.