Check If a Key is Pressed
-
Introduction
You can check if a key is pressed using the following 2 boolean blocks in the sensing category:
https://cdncreaticodecom.b-cdn.net/scratch-gui-projects/forum/8e2d4b02-9857-455e-acee-90ed6c591410.png" width="400" style="border-radius: 5px; border: 1px solid #29622d;">
The “Key [Selection] pressed?” Block
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.
The “Key [Input] pressed?” Block
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.
A Common Mistake
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.
Combined with Forever + If
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.

Check for 2 Keys
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.

Hello! It looks like you're interested in this conversation, but you don't have an account yet.
Getting fed up of having to scroll through the same posts each visit? When you register for an account, you'll always come back to exactly where you were before, and choose to be notified of new replies (either via email, or push notification). You'll also be able to save bookmarks and upvote posts to show your appreciation to other community members.
With your input, this post could be even better 💗
Register Login