How to make a keyPressed into a toggle?

edited July 2016 in Questions about Code

Hello world.

I'm currently using this code to flicker through a folder of imagery in my data folder.

//declare and initialise variables
static final int BACKS = 4;
final PImage[] bgs = new PImage[BACKS];


void setup () {
  size (1920, 1080);
  frameRate (6); //Rate of flickering
    smooth (4);

  //load my imagery
      for (int i = 0; i < BACKS; bgs[i] = loadImage("bg" + i++ + ".jpg")); 

    }

void draw () { 

      image(bgs[int(random(0, BACKS))], 0, 0, width, height);//Set a random Image - the size of the sketch
        if ((keyPressed == true) && (keyCode == UP)) { //THIS IS WHAT STOPS THE LOOP
        noLoop ();

    }
  }

When i press the UP key the looping stops, but is there a way i can press the UP key again for it to begin looping again?

Any help would be great!

Thanks - KOKO.

Answers

  • edited July 2016 Answer ✓
    // forum.Processing.org/two/discussion/17403/
    // how-to-make-a-keypressed-into-a-toggle
    
    // GoToLoop (2016-Jul-03)
    
    boolean paused;
    
    void setup() {
      size(300, 200);
      frameRate(1);
    }
    
    void draw() {
      background((color) random(#000000));
      frame.setTitle("Frame: #" + frameCount);
    }
    
    void keyPressed() {
      int k = keyCode;
    
      if (k == UP)
        if (paused ^= true) {
          noLoop();
          frame.setTitle("PAUSED");
        } else loop();
    }
    
  • With this code, i receive the error : 'expecting EOF found 'if' over the line if (k == UP)

  • do you have all }

    line 26?

  • I do indeed mate, here's what i got.

    //declare and initialise variables
    static final int BACKS = 4;
    final PImage[] bgs = new PImage[BACKS];
    
    boolean paused; 
    
    void setup () {
      size (1920, 1080);
      frameRate (6); //Rate of flickering
        smooth (4);
    
      //load my imagery
          for (int i = 0; i < BACKS; bgs[i] = loadImage("bg" + i++ + ".jpg")); 
    }
    
    void draw () { 
    
      image(bgs[int(random(0, BACKS))], 0, 0, width, height);     //Set a random Image - the size of the sketch 
          frame.setTitle("Frame: #" + frameCount);
    
    }
    
    void keyPressed () ;
    
      int k = keyCode;
    
      if (k == UP)
       if (paused ^= true) {
          noLoop();
          frame.setTitle("PAUSED");
        } else loop();
       }
    
  • Answer ✓

    after line 23 } instead of ;

  • Many thanks amigo's!

Sign In or Register to comment.