keyPressed and keyReleased functions NOT WORKING! Help!

edited November 2016 in Questions about Code

Hi,

I have been trying a ton of different approaches with keyPressed and keyReleased functions. One example is this:

void power ()
{
  float time = 0;
 while(keyPressed)
 {
   if(key == ' ' && power<max_power)
    power +=.01; 
    delay(10);
    println(power);
 }

Here, ideally, every time I press the space bar, and the power is below a certain value, we increment the power.However, even when I RELEASE the space bar, power continues to be incremented until max_power. This doesn't make any sense to me because when any of the keys are NOT being pressed, the while is essentially like while(FALSE). So I don't see how it could continue to be incremented. Not sure if the problem lies in the fact that I put this function in void loop, but whats happening seems very counterintuitive.

I tried this other function as well to count the time, but this does not work either:

 float time = 0;
float final_time;
void setup ()
{

}
void loop ()
{
  println(time+"   "+final_time);

}
void keyPressed()
{
 time = millis(); 
}
void keyReleased()
{
  final_time = time;
  time = 0;
}

Or I've tried this as well to count the time:

float time = 0;
void setup ()
{

}
void loop ()
{
if (keyPressed)
{
  delay(100);
  time+=.1;
}
println(time);
}

But this doesn't work either....

I'm sure there is something very simple behind my error.

Thank you!!!!

Answers

  • edited November 2016 Answer ✓
    • Don't use delay(). It halts draw() and all Processing's input event resolutions! [-X
    • System variable keyPressed is updated once after callback draw() is finished!
    • Sketches w/o draw() are static and renders to the canvas once only!
    • Most OSes got auto-repeat turned on for keyboard. So we need to account for that.
    • We need to subtract current millis() from its previous stored value in order to get the transpired time in milliseconds. :-B

    // forum.Processing.org/two/discussion/19339/
    // keypressed-and-keyreleased-functions-not-working-help#Item_1
    
    // GoToLoop (2016-Nov-28)
    
    int pressedMillis;
    boolean pressed;
    
    void setup() {
      size(300, 200);
      frameRate(60);
    }
    
    void draw() {
      background(pressed? -1 : 0);
      getSurface().setTitle("Pressed: " + pressed);
    }
    
    void keyPressed() {
      if (!pressed) {
        pressedMillis = millis();
        pressed = true;
      }
    }
    
    void keyReleased() {
      print(millis() - pressedMillis, TAB);
      pressed = false;
    }
    
Sign In or Register to comment.