Press space bar to stop animation

I have written this code.

int x;
int y=241;

void setup() {
  size(800, 400);
  background(0);
  
}

void draw() {
  cave();
  stone();
  clumsy();
  
}

void cave() {
  noStroke();
  fill(160);
  rect(0,100,width,200);
}

void stone() {
  color c[] = new color[3];
  int n=0;
  c[0]=color(255, 0, 0); // first color
  c[1]=color(0, 255, 0); // second
  c[2]=color(0, 0, 255); // third
  for(int i=0; i<width; i+=30){
    stroke(0);
    fill(c[n]);
    rect(i,100,30,30);
    rect(i,300,30,30);
    n++;
    if(n>2) n=0;
  }
}

void clumsy(){
  fill(0);
  ellipse(x+30,y-5,80,45);
  fill(#F3F156);
  rect(x,y,58,58);
  fill(#90F614);
  rect(x+5,y+10,10,10);
  rect(x+40,y+10,10,10);
  fill(#EF1A1A);
  rect(x+15,y+30,25,15);
  x++;
  if(x>width){
  x=0;}

}

void keyPressed() {
  if (key == CODED) {
    if (keyCode == UP) {
      if (y == 241){
      y-= 100;
      }
    }
  }
   if (keyCode == DOWN) {
      if (y == 141){
      y+= 100;
      }
    }
  
    
 
}


the character is moving horizontally. now i want to stop moving by pressing space and again want to start by pressing space. How can be it possible? please anyone help me with this problem.

1 Like

You need a state variable in you sketch that keeps track on if you want to make the guy move or not.

Try this example below. The boolean variable play control the state of the program a draw something only if it is set to true.

boolean play;

void setup() {
  play = true;
  frameRate(15);
}

void draw() {
  if (play) {
    background(random(255));
  }
}

void keyPressed() {
  play = !play;
}
2 Likes

Thanks a lot for ur great help