Tuesday, October 28, 2008

AS3 02 - Listening to Keyboard...

Now that we have a basic idea of starting and writing a simple trace feature in CS4 [in the previous post], let's move on to something more interactive. Instead of tracing out the 'Hello World' all the time... let's make flash trace out based certain vulgar words of wisdom whenever we hit certain key.

Now.. shall we start bratss ladies and gentlement? Let's start with the opening of Flash CS3/4 .... blah blah... up until the part where you already know to bring out the AS editor.

Now before we proceed further let me tell you a story of a enlighten you on certain things which are primarily improtant in AS3. The blank screen which appears everytime you startup Flash is referred to as 'stage' by the AS. You can get the width of the flash document by tracing out "stage.stageWidth"




Referring to the title of this post, I guess you should be wondering what does this have anything to do with the so call 'stage'? Well, the stage is where everything happens.. (not really true but it's a good way to think about this now... ). The stage needs to listen for any events that happen. I repeat... the stage needs to listen to events that happen... the STAGE LISTENS to EVENTS that happen... I think by now you should get the degree of the importance of that statement. What does this 'stage' listen to anyway? Well, for starters, keystrokes...

How do we have this 'stage' listens to keystrokes? We simply add an event listener...
yeah it's that simple... not...
you add this line into the AS editor


stage.addEventListener(KeyboardEvent.KEY_DOWN, displayPress);
function displayPress(event:KeyboardEvent)
{
trace('Press');
}



What happens here is the 'stage' has been added a listener... which is the 'KeyboardEvent.KEY_DOWN' It listens to the keyboard events and wait for each key presses through the 'KEY_DOWN'. When the 'stage' hears a 'KEY_DOWN' pressing of a key by the user, it calls the 'displayPress' function. The 'displayPress' function traces out the word 'Press' to the output window.

So run test the script and press the 'spacebar' you can see the word 'Press' appears each time you press the 'spacebar'.

You might be wondering 'Eh? How come only the spacebar works? I didn't specifically listen only to the spacebar...' Well, there is a truth in this... when running in test movie mode, many of the shortcut keys still point back to the main Flash App window. To disable this while testing a movie, simply run the test and go to 'Control->Disable Keyboard Shortcut'. Try pressing any keys now... you get the idea?


Oh... and all said and done if you somehow have problem running the script, just take into consideration that AS3 is CASE SENSITIVE! This means keywords like KeyboardEvent is spelled with the capital intact. Do not ask me why.. as if I am responsible for the damn AS3 language.....

No comments: