How do I time animations when i'm using an array?

edited April 2017 in Questions about Code

I have here code that randomly either increments or decrements an x value using an array and a loop. The loop goes through and picks either an incrementation or a decrementation at random. It then stores that in an array. It goes through 4 loops and outputs 4 x values at each loop. I then use those 4 values and put them in 4 vertex(). The desired result is a shape where each vertex moves about randomly on the canvas.

What I would like to implement is a time delay on the change between increment and decrement. I want to make each point travel in one direction for at least 3000 milliseconds before it might change direction again. I have tried using an if-statment that checks if 3 seconds have passed before it runs the part of the code that randomly chooses an increment or a decrement. The problem is that it only checks every 3000 milliseconds overall, rather than checking if 3000 milliseconds have passed for each single x-value. Basically what I need is for the code to check each spot in the x[] array and see if 3000 milliseconds have passed since it randomly incremented or decremented. Hope I've explained in enough detail.

Here's the code I have written:

int lastTimeCheck;
int timeIntervalFlag = 3000; 
float[] x = new float[4];
float[] incr = new float [4];
void setup() {
  smooth();
  size(500, 707);
  stroke(255);
  lastTimeCheck = millis()/4;
  noFill();
}

void draw() {
  background(49, 48, 48);

  for (int i = 0; i < 4; i++) {

    if ( millis() > lastTimeCheck + timeIntervalFlag ) {
    lastTimeCheck = millis();
    float ran = random(2);


    if (ran > 1) {
      incr[i] = 0.5;
      incr[i] = incr[i]*-1;
    } else if (ran < 1) {
      incr[i] = 0.5;
    }
   }


    println("i ran");

    if (x[i] > width || x[i] < 0) {
      incr[i] = incr[i]*-1;
    }



    x[i] = x[i] + incr[i];



    // println(x[i] + "loop" +i+ incr[i]);
  }
  beginShape();
  vertex(x[0]+20, 40);
  vertex(x[1]+20, width-40);
  vertex(x[2]+20, height-40);
  vertex(x[3]+20, 100);


  endShape(CLOSE);
}
Tagged:
This discussion has been closed.