How to delay part of the code in draw()?

I code a polarline function and use a Slider class to control the number of the lines. When I use delay() to make the image change slowly, the Slider gets slowly and hard to drag. So how can I slowly the image changing rate and not affect the Slider?

float time = 0;
float timeIncrement = 0.5;
float theta = 0; 
float thetaIncrement;
int lineNum;
float[] line;
float[] x;
float[] y;
Slider thetaIncrementSlider; 

void setup() { 
  size(600, 600, P2D);
  smooth(8);
  thetaIncrementSlider = new Slider(30, 100, 4);
} 

void draw() { 
  background(255);
  thetaIncrement = thetaIncrementSlider.value;
  lineNum = int(360/thetaIncrement);

  line = new float[lineNum];
  x = new float[lineNum];
  y = new float[lineNum];

  thetaIncrementSlider.display();
  polarLine();
  delay(500); // this slowly the changing rate of polarline, but Slider gets slowly and hard to drag
}

void polarLine() {
  stroke(0);
  strokeWeight(2);
  stroke(255, 50, 100);

  for (int i=0; i < lineNum; i++) { 
    line[i] = random(200);
    time += timeIncrement;
  }

  for (int i=0; i < lineNum; i++) {
    x[i] = line[i] * cos(radians(theta));
    y[i] = line[i] * sin(radians(theta));
    line(width/2, height/2, width/2+x[i], height/2+y[i]);
    theta += thetaIncrement;
  }
}

class Slider {
  float x, y;
  float sliderX;
  float value;

  Slider(float x, float y, float value)
  {
    this.x = x;
    this.y = y;
    this.value = value;
    sliderX = x+value*4;
  }

  void display()
  {
    noFill();
    stroke(0);
    rect(x, y-3, 400, 4);
    fill(255);
    circle(sliderX, y, 12);

    if (this.isInside(mouseX, mouseY) && mousePressed) { 
      sliderX = constrain(mouseX, x+1, x+400);
      value = (sliderX-x)/4;
    }

    // text display
    textSize(14);
    fill(0);
    textAlign(LEFT);
    text(0, x, y+20);
    textAlign(RIGHT);
    text(100, x+400, y+20);
    textAlign(CENTER);
    text(int(value), sliderX, y-15);
  }

  boolean isInside(float mx, float my) {
    if ( mx>=x && mx<=x+400 && my>=y-20 && my<=y+20) return true;
    else return false;
  }
}

Using delay() will stop the whole sketch.
One of the various possibilities to overcome this is using the following if block where skip will skip the number of frames making the animation slower.

int skip = 10;
if (frameCount % skip == 0) { 
  // code
}
1 Like

Yeah, delay() is bad, don’t use it at all

You could also make an easing between slider and display

Chrisir

1 Like

Hello,

  • Look up reference to delay() and do not use it in this case.
    https://processing.org/ < References, examples and tutorials

  • Initialize or visualize the consequences.
    Set x and y to zero at the start of polarLine();

  • Keep it simple when writing code
    line[i] = 150; //Fixed length used in development; replaced with random length later.

  • Rinse and repeat.

Works.

:)

1 Like