Search code examples
actionscript-3keyboard-eventsstage

Move the circle in as3


I already have the graphic with image on the screen and I wanted to it to move when I pressed the arrows on keyboard.

But it seems the listener is not running and there is no error.

Here is the code:

package
{
    import flash.display.Loader;
    import flash.display.Sprite;
    import flash.events.Event;
    import flash.display.BitmapData;
    import flash.events.KeyboardEvent;
    import flash.ui.Keyboard;
    import flash.net.URLRequest;

    /**.
     * ....
     * @author Kaoru
     */

    [SWF(width = '800', height = '600', backgroundColor = '#000000', frameRate = '24')]

    public class GameManager extends Sprite 
    {
        var myBitmap:BitmapData;
        var imgLoader:Loader;
        var circle:Sprite;

        public function GameManager():void 
        {
            circle = new Sprite();
            imgLoader = new Loader();
            imgLoader.load(new URLRequest("../lib/fira_front.png"));
            imgLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, drawImage);
            addEventListener(KeyboardEvent.KEY_DOWN, onKeyDown);
        }

        private function drawImage(e:Event):void
        {
            myBitmap = new BitmapData(imgLoader.width, imgLoader.height, false);
            myBitmap.draw(imgLoader);

            circle.graphics.beginBitmapFill(myBitmap, null, true);
            circle.graphics.drawCircle(50, 50, 10);
            circle.graphics.endFill();
            addChild(circle);
        }

        private function onKeyDown(e:KeyboardEvent):void
        {
            if (e.keyCode == Keyboard.LEFT)
            {
                circle.x += 5;
            }

            else if (e.keyCode == Keyboard.RIGHT)
            {
                circle.x -= 5;
            }

            if (e.keyCode == Keyboard.UP)
            {
                circle.y += 5;
            }

            else if (e.keyCode == Keyboard.DOWN)
            {
                circle.y -= 5;
            }
        }
    }
}

Solution

  • You need to add it to stage like so,

    stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyDown);
    

    I have modified your code like so:

    Always check for ADDED_TO_STAGE first and then proceed,

    public function GameManager():void 
    {
          addEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
    }
    
    private function onAddedToStage(e:Event):void
    {
          circle = new Sprite();
          imgLoader = new Loader();
          imgLoader.load(new URLRequest("../lib/fira_front.png"));
          imgLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, drawImage);
          stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyDown); //This line is modified
    
          removeEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
    }