Check If a Key is Pressed
CreatiCode last edited by info-creaticode
You can check if a key is pressed using the following 2 boolean blocks in the sensing category:
If the specified key is pressed down at the moment this block is played, then it will report “true”; otherwise, it will report “false”.
You can click any key in the dropdown to select it:
If you select the “Any” key, then this block will report “true” if any key is pressed.
With this block, you can specify the key by typing instead of selecting from the dropdown. You can also use a variable as the input:
Note that upper case and lower case letters are treated as the same for this block.
One common mistake is to check for the key press in a single “if” block like this:
This won’t work because the program will run through the “if” and “key pressed?” blocks very quickly when you click the green flag button. Therefore, if you press the right arrow after clicking the green flag, the program will not respond to you, because it has already ended.
Most of the time, the correct way is to use the “key pressed” sensing block together with a forever block and an “if” block. This way, the program will repeatedly check if a key is pressed.
For example, we can turn the ball sprite left when the left arrow key is pressed, and turn it right when the right arrow key is pressed.
You can also check if 2 keys are both pressed at the same time. For example, when both the “a” and “w” keys are pressed, turn the ball. If you only press one key, then the ball will not turn.