user1805430
user1805430

Reputation: 107

Clicking button using keyboard in AS3

I am trying to do this by clicking on button using 'A' key in keyboard. I created two frames for this button but the code doesn't work, although there is no error.

Do I need to put anything in my main class? Can anyone help to fix this?

package  {

    import flash.display.MovieClip;
    import flash.events.MouseEvent;
    import flash.display.Sprite;
    import flash.display.Stage;
    import flash.events.Event;
    import flash.events.KeyboardEvent;
    import flash.ui.Keyboard;

    public class controlButton extends MovieClip {      

        public function controlButton() {
            // constructor code
            this.addEventListener(KeyboardEvent.KEY_DOWN,clickDown);
            this.addEventListener(KeyboardEvent.KEY_UP,clickUp);
        }

        public function clickDown(event:KeyboardEvent):void{

         // if the key is A
            if(event.charCode == 65){
                this.gotoAndStop(2);
            }
        }

        public function clickUp(event:KeyboardEvent):void{

         // if the key is A
            if(event.charCode == 65){
                this.gotoAndStop(1);
            }
        }

        public function changelabel(newLabel:String):void{

            this.label.text = newLabel;
        }
    }
}

Upvotes: 0

Views: 1342

Answers (1)

KumoKairo
KumoKairo

Reputation: 678

Your button will never receive any KeyboardEvent. You should add your event listeners directly to the stage. Of course, you have to obtain a link to the stage. Anyways:

package {

import flash.display.MovieClip;
import flash.events.MouseEvent;
import flash.display.Sprite;
import flash.display.Stage;
import flash.events.Event;
import flash.events.KeyboardEvent;
import flash.ui.Keyboard;


public class controlButton extends MovieClip {


    public function controlButton() {
        // constructor code
        addEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
    }

    private function onAddedToStage (e:Event):void
    {
        removeEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
                    //stage is no longer null here
        stage.addEventListener(KeyboardEvent.KEY_DOWN,clickDown);
        stage.addEventListener(KeyboardEvent.KEY_UP,clickUp);
    }


    public function clickDown(event:KeyboardEvent):void{

     // if the key is A
         if(event.charCode == 65){
            this.gotoAndStop(2);
        } 


    }

    public function clickUp(event:KeyboardEvent):void{

     // if the key is A
         if(event.charCode == 65){
                this.gotoAndStop(1);
             }
    }



    public function changelabel(newLabel:String):void{

        this.label.text = newLabel;
    }
}

}

As you can see, you should add KeyboardEvent listeners to the stage right after the Event.ADDED_TO_STAGE fires.

Upvotes: 3

Related Questions