Key detection

id: 751322

category: Help with Scripts

posts: 5

So, I'm making a game where it needs to detect which key has been pressed.
Not with:
<touching [ v] ?>
For example, I press the key “a”, and it shows on a variable what key I pressed: a
-stxllxr -stxllxr loading
define last key pressed
set [i v] to (1)
repeat (length of [abcdefghijklmnopqrstuvwxyz 1234567890]
if <key (letter (i) of [abcdefghijklmnopqrstuvwxyz 1234567890]) pressed?> then
set [last key pressed v] to (letter (i) of [abcdefghijklmnopqrstuvwxyz 1234567890
end
change [i v] by (1)
this is the simplest way to detect the last key pressed, however holding down b then pressing a breaks it, so I recommend addjng a wait until after the custom block, not inside the custom block since the custom block needs “run without screen refresh”.

-stxllxr wrote:

define last key pressed
set [i v] to (1)
repeat (length of [abcdefghijklmnopqrstuvwxyz 1234567890]
if <key (letter (i) of [abcdefghijklmnopqrstuvwxyz 1234567890]) pressed?> then
set [last key pressed v] to (letter (i) of [abcdefghijklmnopqrstuvwxyz 1234567890
this is the simplest way to detect the last key pressed, however holding down b then pressing a breaks it, so I recommend addjng a wait until after the custom block, not inside the custom block since the custom block needs “run without screen refresh”.
I did this, but. The variable “i” was set to 1, meaning it will only work if the key “a” was pressed. If I set it to 2, then it only works if I press the letter b.
-stxllxr -stxllxr loading

DangerPuppy10 wrote:

I did this, but. The variable “i” was set to 1, meaning it will only work if the key “a” was pressed. If I set it to 2, then it only works if I press the letter b.
I forgot to add a change i by one after the if block, editing now…
i kinda made it but a little bit weird
https://scratch.mit.edu/projects/992550669/
check this out