how do you make an event listener that only listends to a specific key pressed? i want only the space key to have effect and the left mouse button for a different event. there seems to be only one event for all key presses.
Printable View
how do you make an event listener that only listends to a specific key pressed? i want only the space key to have effect and the left mouse button for a different event. there seems to be only one event for all key presses.
capture the keyCode of the spacebar using a KeyBoard Event- i can't recall which is the spacebar, but you on the event listener, you can get it with a simple trace:
addEventListener(KeyboardEvent.KEY_UP,keypressed);
private function keypressed(e:KeyboardEvent):void
{
trace(e.keyCode)//gives a numeric value representing which key is released
}
ok i got the number, now what?
use an if condition; if its the number you want, do stuff, otherwise do nothing.
is there no way to just put it in the eventlistener?
and what event is for mouse release and click?
Your problem inspired me, so I slacked off at work to build a SpecificKeys class which lets you add event listeners for specific keys without having to use a big if/else or switch statement.
I've attached a zip with the classes and an example. The example could have been done more clearly, I suppose.
Hotness - as usual. Thanks Flax!
5TonsOfFlax: how do i acess the code in the zip file? i have flash cs3... sory im newb
The zip file contains the development directory I used when I wrote it. You don't need most of the files in there. The simplest way to use it would be to unzip to a directory somewhere, then alter your flash classpath to include the src folder (under publish settings). You can then import me.cosmodro.utils.* and get access to SpecificKeys and SpecificKeyEvent.
BUT... I think that this will not really answer the question you posed in your previous thread. You may find SpecificKeys useful to hook your event to a particular keypress (such as "A"), but you still need to know how to attach the listeners in the first place. You can take a look at the Main.as file included in the zip to get an example of that. I also did a short writeup of this class on my blog: http://cosmodro.me/blog/2008/sep/2/specific-keys/
The important part is this:
You initialize SpecificKeys with a reference to the stage. At the moment it does not support key listeners on any more specific level.Code:SpecificKeys.init(stage);
var specKeys:SpecificKeys = SpecificKeys.getInstance();
//...
specKeys.addEventListener(SpecificKeys.getEventID(KeyboardEvent.KEY_DOWN, "A"), hilite);
thanks for ur reply!!
i will give it a try.
so i guess the code that i tried to write up above won't work to what i am trying to do at all? but will need a seperate code instead?