Navigation

    CreatiCode Scratch Forum

    • Register
    • Login
    • Search
    • Categories
    • Recent
    • Tags
    • Popular
    • Users
    • Groups
    • CreatiCode

    Check If a Key is Pressed

    2D Blocks
    1
    1
    844
    Loading More Posts
    • Oldest to Newest
    • Newest to Oldest
    • Most Votes
    Reply
    • Reply as topic
    Log in to reply
    This topic has been deleted. Only users with topic management privileges can see it.
    • info-creaticode
      CreatiCode last edited by admin

      Introduction

      You can check if a key is pressed using the following 2 boolean blocks in the sensing category:

       
       

      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”.

      p.gif

      You can click any key in the dropdown to select it:

      p.gif

       
      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:

      p.gif

       
      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:

      p.gif

      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.

      p.gif

       
       

      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.

      p.gif

      1 Reply Last reply Reply Quote 0
      • First post
        Last post