Skip to main content
August 26, 2013
Answered

How to add Mouse and Keyboard Event in same function?

  • August 26, 2013
  • 1 reply
  • 1365 views

Hi All,

I have a 3d images sequence  which i want to rotate with mouse click and drag.

I am so far successful with that.

What should I do now as I also want to add Keyboard event to it.

Please help.

Thanks in advance.

This topic has been closed for replies.
Correct answer moccamaximum

Sorry. My mistake! forgot to post the code.

var key:uint = e.keyCode;

The code is:

var key:uint = e.keyCode;

images.addEventListener(KeyboardEvent.KEY_DOWN, keyPressed)

function keyPressed(e:Keyboard):void
{
if(key==37){
  images_mc.gotoAndStop(images_mc.currentFrame - 1)
}else if(key==39){
  images_mc.gotoAndStop(images_mc.currentFrame + 1)
}
}


the scope of e is only inside the function,

so when you write

var key:uint = e.keyCode;

Flash doesn`t know of any object called e

you have to rewrite like so:

var key:uint;

and then inside the keyPressed function you write:

...

key = e.keyCode

if(key==37){...

Beware of using any keyWords, when in doubt if "key" is a name flash has reserved internally always use a leading underscore (_key)

1 reply

Inspiring
August 26, 2013

you can basically set up one function to handle all differnent kind of events.

so lets say you have setup an eventlistener like this:

sequence.addEventListener(MouseEvent.CLICK, handleEvent);

you can simply setup a keyboardListener to the stage that has the same name.

stage.addEventlistener(KeyboardEvent.KEY_UP, handleEvent);

and then in the handleEvent (which has been generalized to the class which both event types inherit from) function you write

function handleEvent(e:Event):void{

    switch(e.type){

        case "click": trace("Stage was clicked");

              //write your Mouse Logic

               break;

        case "keyUp": trace("Keyboard was used");

            //write your keyBoard Logic

               break;

    }

}

August 26, 2013

Thank you for your help.

But I am getting this error.

Scene 1, Layer 'Layer 2', Frame 1, Line 50 1120: Access of undefined property e.

Please help.

Inspiring
August 26, 2013

what does line 50 say?