Fade Out with No Flicker

Hi. Im using the following code, and I want my shapes to fadeout after an amount of time. But they flicker before they fade out completely. Does anyone know why this is happening?

ArrayList<Balls> balls = new ArrayList<Balls>();

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

void draw() {
  background(0);
  for (int i=0; i<balls.size(); i++) {    
    balls.get(i).setTimer();
    balls.get(i).drawBalls();
    if (balls.get(i).timerCheck()) {
      balls.remove(i);
    }
  }
}

void mouseDragged() {
  balls.add(new Balls(mouseX, mouseY));
}

class Balls {
  float x, y;
  color colors, colorsStroke;
  int timer;
  float fadeOut = 1.;
  float randomLife = random(80, 200);

  Balls(int mousex, int mousey) {
    colors = color(random(255), random(255), random(255));
    colorsStroke = color(random(255), random(255), random(255));
    rectMode(CENTER);
    x = mousex;
    y = mousey;
  }

  void setTimer() {
    timer++;
  }

  boolean timerCheck() {
    boolean check = false;
    if (timer>randomLife) {
      fadeOut = fadeOut - 0.01;
    } 
    if (fadeOut<=0.) {
      fadeOut = 0.;
      check = true;
    }
    return check;
  }

  void drawBalls() {
    strokeWeight(2);
    stroke(colorsStroke, 255*fadeOut);
    fill(colors, 50*fadeOut);
    pushMatrix();
    translate(x, y);
    ellipse(0, 0, 30, 30);
    popMatrix();
  }
}

Answers

  • edited May 2015 Answer ✓
    • There's a bug in your draw()'s for ( ; ; ) loop!
    • Dunno whether it got anything to do w/ your flicker complain though... :-/
    • When using remove(), we need to use a backwards for ( ; ; ) loop instead.
    • That is, beginning from List's tail end and rewinding to its head start:
      for (int i = balls.size(); i-- != 0; ) { }
    • Also, it makes the whole traversal faster if we cache List's get(): Ball b = get(i);
Sign In or Register to comment.