How to pause/play a sketch with the same button?

Hi guys, I'm trying to implement a pause/play for a sketch with the same key, for example if I press p the sketch should stop and if I press p again, the sketch should start again. So far I used the noLoop()/loop() to do this but with two different keys (p for pause, r for start). It does work if I use keyPressed() and keyReleased() but this means to hold down the key but this doesn't answer my question. Also in the pause mode I used redraw() for a single step while noLoop() and works good. Here is some code I tried so far with two different keys:

public void keyPressed(){

if ( key == 'p' )
    noLoop();
if ( key == 'r' )
    loop();
if ( key == 's' )
    redraw();

}

And this is the code with the same key:

public void keyPressed(){

if ( key == 'p' )
    noLoop();
if ( key == 'p' )
    loop();
if ( key == 's' )
    redraw();

}

In this case when I press key it doesn't have any effect. And the last one I tried is this:

public void keyPressed(){

if ( key == 'p' )
    noLoop();
else
    loop();
if ( key == 's' )
    redraw();

}

In this case when I press 'p' it stops the sketch but is doesn't play again. Because of the 'else' it plays again when I press any key including 's' which suppose to be just for a single step. Any help is more than welcome. Thanks!

Answers

  • edited July 2017 Answer ✓
    /** 
     * Looping Pause (v1.1)
     * GoToLoop (2017/Jul/19)
     *
     * Forum.Processing.org/two/discussion/23531/
     * how-to-pause-play-a-sketch-with-the-same-button#Item_1
     */
    
    void setup() {
      size(800, 600);
      frameRate(4);
    }
    
    void draw() {
      background((color) random(#000000));
    }
    
    void keyPressed() {
      final int k = keyCode;
      looping ^= k == 'P';
      redraw = k == 'S';
    }
    
  • Is looping a keyword or do we have to evaluate it?

  • Answer ✓

    This is what I would do in your case.

    Kf

    if ( key == 'p' )
        looping = !looping;
    
    if ( key == 's' && looping==false )
        redraw();
    
  • Answer ✓

    if(looping){

    if(key=='p'){

    looping=false;

    noLoop();

    }

    else {

    // looping is false

    if(key=='p'){

    looping =true;

    loop ();

    }//if

    }//else

  • Thanks guys. All your answers work good.

Sign In or Register to comment.