Hello, I have this code and I don't know how to restart the sketch using R key

56 Views Asked by At
    
     if(toggle == 1){
  
    fill(150,10);
    rect(width+435,400,200,height);
    fill(0);
    textSize(20);
    text(" R = Restart",1120,500);  
  }
  }
}
void keyPressed()
{
if(key=='R' || key == 'r')
{
 
  
}

}


I have done everything that I know and still haven't reached a point. I have done and approached my problem with a lot of methods and neither one of them was true for my case.my problem is with the r which stands for restart the sketch.

2

There are 2 best solutions below

0
On

Your sketch depends on frameCount. Resetting the sketch would mean resetting the frameCount. Unfortunately, the framecCunt cannot be reset. You have to implement your own frameCount:

Add a variable:

int myFrameCount = 0;

Increment the variable every frame and replace frameCount with myFrameCount in your code:

void draw() {
  myFrameCount += 1;

  // [...]
}

Reset the myFrameCount when r is pressed:

void keyPressed() {
  if (key == 'r')  {
    myFrameCount = 0;
  }
}

Complete code:

int toggle =1;
int width=640;
int height=360;
int myFrameCount = 0;

void setup() {
  size(1280, 720);
}

void draw() {
  myFrameCount += 1;
  background(255);
  noStroke();
  fill(0);
  float s=5.0;
  for (int i=0; i<height; i++) {
    for (int j=0; j<width; j++) {
      float x=noise(s*(j+5*myFrameCount)/width, s*i/height);
      float y=noise(s*j/width, s*(i+3*myFrameCount)/height);
      float x1=j + 18*map(x, 0, 1, -0.6, 0.6);
      float y1=i + 18*map(y, 0, 1, -0.6, 0.6);
      float t= map(cos(0.007*myFrameCount), -1, 1, 0.01, 0.0005);  
      float theta= lerp(noise(t*x1, t*y1 ), noise(4*t*x1, 4*t*y1 ), 0.2);
      fill(map( cos(theta*0.04*(1+0.004*myFrameCount)/t), -1, 1, 0, 255));
      rect( j*2, i*2, 2, 2);
    }
  }
}

void keyPressed() {
  if (key == 'r')  {
    myFrameCount = 0;
  }
}
0
On

As mentioned, frameCount is the only temporal variable in Your program.
And at least in v4 Processing, You can set frameCount. When You will set it to 0 it will be an equivalent of program "reset":

void keyPressed() {
  if (key=='R' || key == 'r') frameCount = 0;
  println(frameCount);
}