Fire Weapons with Key.addListener

Creating a REAL Key Listener

Well, this is why the firing function wasn't included in the previous lesson! It's about to get a bit more challenging. Let's delete that last if statement and start over.

DELETE THIS:

if(Key.isDown(Key.SPACE)){
fire();
}

We're going to create a new group of code with quite a few more statements than what we had above. Take a deep breath and get ready to learn!

First, we'll declare a new variable with the Object data type. In fact, it's just a new Object with the name keyListener:

Notice the variable name keyListener is rendered in black in the Actions window. It's not a built-in name reserved by Flash. I decided to call it keyListener because that's gonna be it's job... to "listen" for a key event.

The key event we'll have Flash listen for is onKeyDown. Any time a key is pressed down, we'll run a function:

Now we use an if statement to find out which key was pressed. Flash has a built-in function called Key.getCode() which returns a specific code for each key. We'll see if that code is Key.SPACE:

Now we'll call the fire function:

And finally, we need to add the specific listener for our keyListener. Notice how this statement goes outside all the function:

Wow... that was some work! Don't be discouraged if you feel like you don't "get" it. This is just how it's done, and with practice, it will be second nature to you.

Check your work:

Content on this page requires a newer version of Adobe Flash Player.

Get Adobe Flash player