How to Create a Key Tapping Sensor

Материал из Поле цифровой дидактики

It is fairly simple to make a script detecting a key press, such that when you hold a key, an associated action repeats until the button is released. However, if you want to trigger an action only once per time a key is pressed and released, you can use the scripting in this tutorial.

What To Do

Repeating Script

This is an example script which will allow an action to be repeated while a key is pressed:

when flag clicked
forever
if <key [... v] pressed?> then
next backdrop
end
end

A possible issue with this script is that the player may advance by more than one backdrop before they release the key.

You could also use this script to repeat an action while a key is held:

when [... v] key pressed
next backdrop

This might have a smaller issue than the previous script because there is a tiny pause between each triggering of the hat block, although holding a key will still work on most operating systems.

Non-Repeating Script

This is a script which only changes the backdrop once per key press:

when flag clicked
forever
wait until <key [... v] pressed>
next backdrop
wait until <not <key [... v] pressed?>>//this block will stop the script until the key is released
end

This will make its sprite sense the key, perform an action, and wait for the key to be released before checking again if the key is being pressed. You can also change the order of the blocks in the previous script to this:

when flag clicked
forever
wait until <key [... v] pressed?>
wait until <not <key [... v] pressed?>>
next backdrop
end

If you use this example code, the player has to press the key and release it before the backdrop will change.

Advanced Cases

  • The plausibility of the need for a key release detector is not established. Also, there is already a "Uses"

Let's say you are making a platformer, this can be useful when you run into issues

when [... v] key pressed
forever
wait until <not <key [... v] pressed?>>
broadcast [... v]
stop [this script v]

and then you want to make this:

when I receive [... v]
next backdrop

Uses

A key tapping sensor could be useful for many things, such as announcement projects, or projects with only words. It's often important in these projects, that users don't skip through the information quickly, so this script could be useful. If one wants to create a platformer, the first example script (which repeats an action quickly as a key is held) could be used to to create nice, smooth controls.