Strike Force Heroes 2
The explosive sequel to the hit game Strike Force Heroes!
3.94 / 5.00 9,933 ViewsObsolescence
Defeat the enormous mechanical beasts--and become one of them.
4.02 / 5.00 45,756 ViewsKEYBOARD EVENTS
AS3: Main - The Place for Newbies ^_^
AS3 Language and Components Reference - For the Rest of Us! =p
Prerequisites:
INTRO
This tutorial will hopefully shed some light on how to handle key presses for newbies to action script. Most of us know that there are a growing number of Key classes surfacing around the Internet which provide open source code to use in an external .as file. These files are very convenient for people who coded in AS2 prior to learning AS3. We did all miss Key.isDown and Key.isUp, but I don't think new comers to AS3 should have to be confined to using the old way of doing things.
For one, I think that a person who is relatively new to Flash CS3, and coding in general, would have a difficult time trying to learn first how to set up an outside class, and then accessing it/using it properly from within Flash. Therefore, I think for that the newbs and more experienced users alike, there should be some easier to access documentation concerning the new way of testing keyboard input.
// All people who are newbies to action script should skip until there is a place that says "//STOP HERE!"
Yes, using a new version of the old method works just fine. Yes, it might actually be a little better than simply using the basics listed here. However, outside the scope of this tutorial, it would be easy enough for anyone recreate the isDown/isUp effects if they understand the concepts listed here. Therefore, let's not start a flame war saying thinks like:
"Senocular and dELtaluca pwn your n00ber code! Go commit teh suisidez lamer > = - ("
understand that I give both of these guys a huge amount of respect for helping many people make the leap from AS2 to AS3 a little less intimidating. However, we also need to keep in mind the people who are just learning to code, and therefore don't have the foundation of knowing AS2 to build their knowledge of AS3 on. Why have a newbie go through the process of learning about Classes, importing stuff, accessing imported stuff, initializing all of that properly, etc. etc., when they only want to hit test 1 key on the key board and have their movie replay?
//STOP HERE!
Using the keyboard in AS3 may appear to be a difficult task, but I assure you that with some practice you will begin to see how easy it is. There are better methods for using the keyboard than the following, but this is a good place to start. Without knowing how to use Keyboard Events you wouldn't ever really understand how the better methods work. Let's first take a look at how to setup your Flash Project to be able to accept input from the keyboard.
* IMPORTANT! *
Make sure that you are using Flash CS3 or higher, and that you are publishing your swiff file to work with AS3 and Flash Player 9 and up.
PART 1 - SIMPLE DETECTION
We begin by placing the following code on the first frame of the mainTimeLine:
stage.addEventListener(KeyboardEvent.KEY _DOWN,checkKeysDown);
stage.addEventListener(KeyboardEvent.KEY _UP,checkKeysUp);
/*These two lines of code setup the .swf file to use two functions (checkKeysUp and checkKeysDown) for keyboard input. the most important part is "stage." Often times in Flash you can simply add things to "this" (this being the main time line), but you must attach these listeners to the stage, or else they won't work properly.*/
Now, this won't actually do anything because you have not yet created the functions needed to use these listeners. The following does that.
function checkKeysDown(event:KeyboardEvent):void{
trace("You pressed key: "+event.keyCode);
}
function checkKeysUp(event:KeyboardEvent):void{
trace("You released key: "+event.keyCode);
}
/*These two functions trace the code of any key you press and/or release*/
These two function are very basic. They will trace out the key code of any key that you press and/or release. Just make sure these two function are defined in teh same place that you added those two listeners. If you've done everything right, then your end product will be a blank screen that traces the key codes of keys you press on the keyboard.
PART 2 - ADVANCED DETECTION
Okay, now that you've mastered the idea of testing basic keyboard input let's move on to a more versatile application.
var keyArray:Array = new Array();
var i:Number;
for(i=0;i<222;i++){
keyArray.push([i,false]);
}
stage.addEventListener(KeyboardEvent.KEY _DOWN,checkKeysDown);
stage.addEventListener(KeyboardEvent.KEY _UP,checkKeysUp);
this.addEventListener(Event.ENTER_FRAME,
UpdateScreen);
function UpdateScreen(event:Event):void{
if(isKeyDown(39)==true){
trace("Pressed");
}
if(isKeyDown(39)==false){
trace("Released");
}
}
function checkKeysDown(event:KeyboardEvent):void{
keyArray[event.keyCode][1]=true;
}
function checkKeysUp(event:KeyboardEvent):void{
keyArray[event.keyCode][1]=false;
}
function isKeyDown(X){
return keyArray[X][1];
}
Basically, the above script runs through and checks data in an array. When you press or release a key, data in that array changes. You can test different keys by using the function isKeyDown(X), where X is any keyCode. In the above example, you are testing the right arrow key.
This code looks a lot harder than it is =). If you read the prerequisites, then you know that UpdateScreen is going through and checking every frame of your animation/game for if the Right Arrow key is either down or up. IT does this, by checking the value of the key's value in the array keyArray. If you want to check for a key being up, use:
if(isKeyDown(keyCode)==false){//do stuff};
Test for "true" if you want to use it as being pressed. This script is by no means the best way to handle key presses, but it works well enough for what you understand right now. Perhaps once you've gained more knowledge of Flash you can write your own process for handling keyboard input which goes far beyond the efficiency of this script.
For those of you who want to see some other ways of handling Keyboard input, see the following links:
awesome tutorial. pretty useful.
I aint got no sig!
Nice job! I looked at senocular's and other guys tutorial, and yours seems to be the best(and simplest) method to do things.(now, to learn it =])
Insanity is a true sign of genious...
At 4/24/08 09:41 PM, Cjross313 wrote: Nice job! I looked at senocular's and other guys tutorial, and yours seems to be the best(and simplest) method to do things.(now, to learn it =])
They're not tutorials or methods, they're implementations for you to use. This is a tutorial explaining them.
Thanks, it really helped understand the concept of Key Events. Thanks again!
Rape l Sin or I R Apelsin, which ever suits me best...
Now I'll Trololo your face with an Apelsin!
Yo, I had a problem where I had to shoot before I could zoom in a game I'm converting to as3, found a simple fix that some may find helpful.
stage.focus=stage;
Programmers are machines that convert caffeine to software.
Man I registered an account to tell ya this. Your post sucks! I aint a flash newbie. I've been dealing with flash like 2 years. Recently I forgot something about keyboard event, then i just google AND it is the first result. THE FACT IS, lots of newbie gonna cry coz your intro is freaking long. There is 90% bullshit and 10% useful information. Un-clear details and "bugs", I mean, come on, cut it out. U KNOW WHAT, the biggest stupid mistake is in this line.
stage.addEventListener(KeyboardEvent.KEY _DOWN,checkKeysDown);
Ya know what's wrong with this line? There's a space between KEY and _DOWN. Jesus, newbie gonna paste this and run the program then error message appears. They gonna cry and wonder why the most fundamental line contains error.
The answer is, because the AUTHOR SUCKS!
At 9/26/11 12:10 PM, stonyau wrote: Man I registered an account to tell ya this. Your post sucks! I aint a flash newbie. I've been dealing with flash like 2 years. Recently I forgot something about keyboard event, then i just google AND it is the first result. THE FACT IS, lots of newbie gonna cry coz your intro is freaking long. There is 90% bullshit and 10% useful information. Un-clear details and "bugs", I mean, come on, cut it out. U KNOW WHAT, the biggest stupid mistake is in this line.
stage.addEventListener(KeyboardEvent.KEY _DOWN,checkKeysDown);
Ya know what's wrong with this line? There's a space between KEY and _DOWN. Jesus, newbie gonna paste this and run the program then error message appears. They gonna cry and wonder why the most fundamental line contains error.
The answer is, because the AUTHOR SUCKS!
I'm sorry that he made you cry, and I'm sorry you still don't understand this stuff, but if you would like help, start a new thread that addresses your problem specifically, instead of making a non-informational post in a very old thread.
Thank you so much, I've been looking for a more efficient way to move my pieces and you helped me easily understand it!
At least one person had benefit of bringing up this topic, while all this information is perfectly documented throughout the web. The most important thing about this is to remember that an object will only create a keyboard event when it has focus. Thats why you attach it to the stage, this object generally has the focus.
Asteroids || Never trust a gay Canadian?
The thing I'm wondering about in your advanced detection is why you have to make so many arrays, when you could just reference the original array number and make that a boolean.
So, instead of making (choosing a number at random):
keyArray[57][1] = true; //when key 57 is pressed
why not just skip making:
keyArray[57][0]= 57 //because this is pointless, you already know it's number 57
and just make:
keyArray[57] = true; //when key 57 is pressed
So that you don't have to mess around with going through another layer of Arrays.
I know you weren't intending to make it completely efficient, but instead of using an OnEnterFrame to check whether a key is being pressed, you should just make it a function that's called whenever a key is pressed or released. So, instead of calling "UpdateScreen", you could rename it "UpdateKeys" and get rid of the Enter_Frame event listener to trigger it. Unless this was supposed to be a combined tutorial.
That being said, I thank you for your tutorial, because it showed me what I was looking for when I seached "AS3 keyboard event" in google. :D
Omit the "e" from my username if you wish... (I sometimes do... but only because I mispell it...)
Status: Ignoring Stupidity... (i.e. Ignoring myself.)