Keyboard input in Game Lab

I have a student that has written some code in gamelab to check for keyboard input. When the user presses the “a”, “w”,“s”,or “d” keys, he makes something happen. He asked me if there was a way to know if they user pressed any other key so that he can play a buzz sound. I tried everything that I could think of to help him, but nothing worked the way I thought it would. He said he would just put in a bunch of if statements for all the other keys, but I know there is a better way.

Here are some of the things that we tried:

if (keyDown(“a”)) target = 25;
else if (keyDown(“s”)) target = 57;
else if (keyDown(“w”)) target = 89;
else if (keyDown("d)) target = 121;
else playSound(“https://audio.code.org/failure1.mp3”);

This plays the failure sound even when no key is pressed.

We need to know there was a key pressed and then check to see if it was the correct key. Is there a method to do this?

Kammie,

After playing around a bit, I couldn’t figure out a way to use the OR ( || ) operator to get multiple keys to make the keyDown method true. Might need to use a bunch of if or elseif statements to get the ode to work for now. I’ll bump this up to people that might know of a better way.

Brad

Kammie,

After sleeping on it - I realized I was looking at the code wrong. There might be a better way - but you can use a complex conditional like: if ( keyDown("q") || keyDown("e") || keyDown("r")) { // play sound } . if you wanted to… its similar to the multiple if and elseif statements, but in one longer one.

Hope that helps!
Brad

1 Like

I was trying to prevent him from having to create an if statement that included every key on the keyboard that he was NOT looking for… that’s a lot of keys!

It would be nice if there was a keydown method that returned the key that was pressed. Then you could store that in a variable and check to see if it is one of the keys you are looking for, otherwise you would play the sound.

With all of the keyDown, keyWentDown, keyWentUp functions that we have, if you create an if statement with them, the else part gets executed when nothing is being pressed.

I’ll just tell him that with the functionality that we have, there is no “easy” way to code this.

Thanks for your help

2 Likes