How to make a delay in processing project?

2019-01-15 23:34发布

问题:

Hi Im using java but Im trying to make a delay that doesn't stop the program but stops that block of code kind of for example if I have it in a method that adds 1 to a variable I want it to add 1 then wait one second then add 1 again but delay() stops the whole program and thread.sleep doesnt work in a processing project.

回答1:

You should not use delay() or Thread.sleep() in Processing unless you're already using your own threads. Don't use it on the default Processing thread (so don't use it in any of the Processing functions).

Instead, use the frameCount variable or the millis() function to get the time that your event starts, and then check that against the current time to determine when to stop the event.

Here's an example that shows a circle for 5 seconds whenever the user clicks:

int clickTime = 0;
boolean showCircle = false;

void draw(){
  background(64);
  if(showCircle){
    ellipse(width/2, height/2, width, height);

    if(clickTime + 5*1000 < millis()){
      showCircle = false;
    }
  }
}

void mousePressed(){
  clickTime = millis();
  showCircle = true;
}

Side note: please try to use proper punctuation when you type. Right now your question is just one long run-on sentence, which makes it very hard to read.