How can I set a KeyPressed delay and randomise it for a limited time?

edited November 2017 in How To...

Hello there! I need to make keyboard inputs fail for a limited time during a game made in Processing. I also need to randomize those failures.

I don't know if the "delay" is the best option. I'm new in Processing and I need it to test my research, so I will be eternally grateful to anyone who can help me!

Answers

  • edited November 2017 Answer ✓

    Do not use delay(). It does not do what you think it does. It is not the function you want. Do not use it. Do not. No. No. No. Do not use delay().

    Let me be very clear: DO NOT USE DELAY().

    What you should use, instead, is a boolean that records if key presses are currently enabled, and a number that represents a time when that boolean should next switch values. You can get the current time represented as a number from the function millis(). You should use millis().

    Here is an example:

    boolean keys_broken;
    int time_to_toggle_keys_broken;
    
    int x, y;
    
    void setup() {
      size(200, 200);
      x = 100;
      y = 100;
      keys_broken = false;
      time_to_toggle_keys_broken = millis() + int(random(3000, 7000));
    }
    
    void draw() {
      background(0);
      if (keys_broken) {
        background(100, 0, 0);
      }
      fill(0, 200, 0);
      ellipse(x, y, 20, 20);
      if ( millis() > time_to_toggle_keys_broken ) {
        keys_broken = !keys_broken;
        time_to_toggle_keys_broken = millis() + int(random(3000, 7000));
      }
    }
    
    void keyPressed() {
      if (keys_broken) { 
        return;
      }
      if ( keyCode == LEFT ) { 
        x -= 5;
      }
      if ( keyCode == RIGHT ) {
        x += 5;
      }
      if ( keyCode == UP ) { 
        y -= 5;
      }
      if ( keyCode == DOWN ) { 
        y += 5;
      }
    }
    

    In short: delay() BAD! millis() GOOD!

  • Ok, I got it. Delay() is the enemy. Bad bad delay(). Thank you!

Sign In or Register to comment.