For other uses, see When () Key Pressed (disambiguation).
When () Key Pressed
when [ v] key pressed
Category Event
Type Hat

The when () key pressed block is a hat block and an Events block. Scripts placed underneath this block will activate when the specified key is pressed.

The keys that can be sensed with this block involve the entire English alphabet (a b c etc.), the number keys ( 0 1 2 etc.), the arrow keys ( ), and the space key. After an update, this block now includes an any option, which allows one to press any key to operate the block.

In the Experimental Viewer, the ↵ Enter key (or ↵ Return key on Macs) could also be sensed.

It is possible to use "hack blocks" which allows editing and changing of buttons that this block can detect.

The block will activate depending on the operating system's settings. For example, if a key is held down, it may or may not repeat afterwards depending on whether or not the user's operating system is set to repeat pressed keys. For this reason, it is best not to make projects that rely too heavily on key repeats given by the block.

Example Uses

This block is used to get input from the player, for a variety of uses.

Some common uses include:

  • Controlling an object
when [space v] key pressed
broadcast (fire v)
repeat (5)
 change y by (5)
  • Typing on a word processor
when [a v] key pressed
switch costume to (a v)
change x by (20)
when [space v] key pressed
broadcast (animation starts v)
play sound (intro v)
  • Moving around a map
when [up arrow v] key pressed
change y by (15)
Note Note: Because of the built-in delay, the <key ( v) pressed?> Boolean is often used for movement, as it will execute its script more rapidly and make movement smoother.

Detecting Mouse Scrolling

When this block is set to sense and , it will also sense mouse scrolling. Additional code can be added so that only mouse scrolls are detected:

when [up arrow v] key pressed
if <not<key (up arrow v) pressed?>> then
  ... // will only detect scrolling up
when [down arrow v] key pressed
if <not<key (down arrow v) pressed?>> then
  ... // will only detect scrolling down


Main article: List of Block Workarounds

This block can be partially replicated with the following code:

when flag clicked
 if <key (wanted key v) pressed?> then
 . . .
Note Note: This workaround is not exact, as the hat block will break off in the middle of a script, but the workaround will not. The built-in delay in the hat block (if the key is held down, there will be a slight pause, followed by a shorter pause) is not inherent in the workaround. Also, the hat block does not require the green flag to be pressed.

A more precise workaround:

when gf clicked
if <key (key v) pressed?> then
broadcast (ready v)
when I receive [ready v]
. . .

See Also

Cookies help us deliver our services. By using our services, you agree to our use of cookies.