We are about to switch to a new forum software. Until then we have removed the registration on this forum.
I want to be able to hold down a key or combination of keys and have it fire repeatedly. I've tried keyPressed as well as keyTyped and they only seem to register the initial event. I then tried keyIsDown() and it's very difficult to get a consistent repeat rate contingent upon the current frameRate. I also tried to throttle the repeat rate by only polling it every n frames but this is inconsistent as well. What's the best way to handle this?
keyPressed=function(){
switch(true){
/* Function Keys */
case keyCode===KEYCODES.UP: colUp(); break;
...
}
Answers
Edit: Note that this is a p5 Java example -- the API is the same but the event model is actually different in JavaScript (p5.js).
One approach that I have found generalized and reliable:
While the flag is set, fire at whatever rate you want.
One way to efficiently store the data for that approach is
Then on keyPressed and keyReleased events you can use:
Now for any combination of keys, you can check the key state.
Here is an old sketch -- it doesn't use keypressed / keyreleased, but only flips states based on taps (a full release). But it gives you the idea. Try loading it up and pressing "qwerty" all at once as quickly as you can, and you can see it go into the map. You could also do this as a class.
Thanks. It's a nice solution (I've used something similar using an array) but it still doesn't answer how to get a consistent keypress rate while polling the frameCount. Unless I'm missing something? I'm using frameCount%5 or some such and it consistently skips or gives me doubles. Any thoughts?
TIA
I don't understand what "polling" means. Could you explain more and perhaps share a concrete example of an MCVE showing the problem that you are having?It sounds like you are saying that you are doing something like this:...but that your output is dropping frames, and so you are missing hits from e.g. this list?...that would be surprising, because as far as I know Processing does not drop frames. Each frame takes as long as it takes, and it then increments by 1 and proceeds to the next one. Also, there isn't a race condition between key events and frames -- all key events are processed before the next frame starts, so if you so any variables updated by key events should be in their new state at the beginning of the next frame....scratch ALL of that -- I just realized that this is a p5.js question, not p5 Java. I defer to people more familiar with the JavaScript event model!
Keyboard repeat rate is not consistent across devices and frame rate is not consistent either; so you might be better off handling repetition yourself. On key down just use a timer to trigger repetition of the key action and stop it on key up.
I think you're right. Everything I've read leads me to the same conclusion. Thanks