Record time a key is held in Processing

135 Views Asked by At

I've searched on so many forums including this one and I can't see to find any answer for this. Many of the solutions given to me looked like this:

void keyPressed(){
  if (key == 'e'){
    t = millis();
  }
}

void keyReleased(){
   if (key == 'e'){
    t = millis()-t;
    println(t);
   }  
}

This is incorrect however because the keyPressed function continuously calls upon millis() when I hold a key. So when the key is released the recorded time prints a number close to zero!

How do I make keyPressed call millis() only once?

1

There are 1 best solutions below

0
Kevin Workman On BEST ANSWER

You could just use a boolean that tracks whether you've already set the value. Something like this:

boolean recorded = false;

void keyPressed(){
  if (key == 'e' && !recorded){
    t = millis();
    recorded = true;
  }
}