What are the advantages of using predefined functions over keywords?

Are there any benefits to using void keyPressed() {} instead of if (keyPressed)? Or void mousePressed() {} instead of if (mousePressed). Or something like that.

And in which situations would you use one over the other?

1 Like

The Processing website has references for these functions.

I suggest going through the references and examples and make a list based on what you observe.
Feel free to modify the code as well to better understand how these functions work.

Insert println() statements in the code (with meaningful data\messages) and monitor the console; this is a useful tool for working through code.

References:
https://processing.org/reference/println_.html

:slight_smile:

1 Like

The fields keyPressed & mousePressed are for when we need some state to be active as long as a key or mouse is being held down.

The callback versions are for when we need something to trigger once for each press or click.

@GoToLoop Oh, so keyPressed() makes it so that you can hold down a key, while keyPressed makes it so that you can just tap a key?

It’s the opposite. :flushed:

1 Like

There are a number of differences. @GoToLoop already give you an accurate summary, but here, to unpack a bit:

One is that keyPressed() and keyReleased() are transition events, and keyPressed is a state.

One is that if(keyPressed) isn’t guaranteed to catch your key event. The key has to be in that state when draw executes. On the other hand, keyPressed() will get the event – regardless of the exact moment that it happens, lag, etc. – because it the event is queued and then processed on during the frame.

From this, another is that keyPressed() can handle multiple key inputs per frame. If your user is typing and you try to handle it in draw with if(keyPressed) input.append(key) then you are probably going to be dropping key presses.

If you mash a bunch of different keys down over time: asdfghlaseuhsvasdkvcxvcmfnlfahe then keyPressed will keep reporting each frame that some key is down. You can even rapidly press the same key aaaaaaaaaaa and have keyPressed be true on multiple consecutive frames, even though the key was up inbetween. If you really want to check for continuous uninterrupted holding down of a key, use the event functions.

void setup(){
  frameRate(1);
}
void draw(){
  if(keyPressed){
    println("draw-press", key);
  }
  println("");
}
void keyPressed() {
  println("func-press", key);
}
void keyReleased() {
  println("func-release", key);
}
2 Likes

Got it, thanks guys!