[beginner] Making one 'thing' instead of the many due to refreshing

edited January 2015 in Questions about Code

Simple programme that creates a circle that gradually increases until it's off screen, then another is repeated.

However, though it looks like one circle getting larger it's of course many circles being drawn slightly larger which gives the appearance of the one circle increasing.

What I would like line 15 to do is set the color value for the circle for it's whole life. Rather than what it currently does which is change with every frame. I understand why it changes, but I don't know how I would go about changing the code so that each circle would be a random color value and hold that value.

I hope that makes sense, here's the code :

float x = 0;

void setup() {
  size(300, 300);
}

void draw() {
  background(255);
  strokeWeight(4);
  ellipseMode(CENTER);
  float a = random(255);
  float b = random(255);
  float c = random(255);
  fill(a,b,c);
  ellipse(150, 150, x, x);
  x += 1;
  if (x == width+120) {
    x = 0;
  }
}

Answers

  • edited December 2014
    int x = 0;
    color c;
    
    void setup() {
      size(300, 300);
      strokeWeight(4);
      ellipseMode(CENTER);
      c = color(random(255),random(255),random(255));
    }
    
    void draw() {
      background(255);
      fill(c);  
      ellipse(150, 150, x, x);
      x++;
      if (x == width+120) {
        x = 0;
        c = color(random(255),random(255),random(255));
      }
    }
    
  • Answer ✓

    Usually this would be done by storing the fill color in a variable and then changing that variable only when needed. In this case there is only one thing that needs a color (the ellipse) and so you don't need to store it

    What is going on in the sketch below is that a fill color is set during setup() before the draw() loop runs. The ellipse uses that fill color until the if statement is true. When the if statement is true then the fill color is picked again

    Let me know if you have questions:

    float x = 0;
    
    void setup() {
      size(300, 300);
    
      // These never change, do them only once in setup()
      strokeWeight(4);
      ellipseMode(CENTER);
    
      // Set the ellipse's fill color now before draw
      fill(random(255.0), random(255.0), random(255.0));
    }
    
    void draw() {
      background(255);
    
      ellipse(150, 150, x, x);
    
      x += 1;
      if (x == width+141) {
        x = 0;
    
        // Pick the ellipse's fill color again
        fill(random(255.0), random(255.0), random(255.0));
      }
    }
    
  • Hi both! New Year happened and wiped me out for a bit... Thanks for the response though.

    @asimes -> that works, thanks very much for explaining too.

Sign In or Register to comment.