When do you use keyPressed as function?

There seems to be multiple ways to use keyPressed.

if (keyPressed == true) { …

or
void keyPressed() { …

When do you use it as function and when not? When and how do you combine both?

Hi,

Looking at the Processing documentation, they say (about keyPressed() :

Note that there is a similarly named boolean variable called keyPressed.

So basically they act the same way but one is a system variable (keyPressed) accessible from everywhere and the other one is a function called when a key is pressed.

It looks that if you check is keyPressed is true in the draw() function, it can trigger multiple times whereas the keyPressed() function is only executing once. It depends on the usage and the problem you want to solve.

I usually prefer using the keyPressed() function as it’s more precise and clear in my code.

Note : Saying :

if (keyPressed == true) { …

can be simplified because keyPressed is already a boolean value so if it’s true then the condition is true then if it’s false the condition is false, so you can directly write :

if (keyPressed) { ...
2 Likes