Question

I'm new to coding and unfortunately my teacher is more programmer than teacher so he is very vague on how to do things. I'm aiming for something simple I have a symbol from my library dragged and dropped directly on the stage as my Background and in the code for the background object I'm trying to add a small arrow for the menu selector that you move with the mouse keys. I know its something simple I'm not understanding so if anyone can help that would be great!

package 
{

import flash.display.MovieClip;
import flash.events.KeyboardEvent;
import flash.ui.Keyboard;
import flash.events.Event;


public class BG extends MovieClip
{

    public var select:Select = new Select ;


    public function BG()
    {
        // constructor code
        addEventListener(Event.ADDED_TO_STAGE, addedToStage);

        addChild(select);
        select.x = 200;
        select.y = 200;
    }

    private function addedToStage(ev:Event):void
    {
        removeEventListener(Event.ADDED_TO_STAGE, addedToStage);
        addEventListener(Event.REMOVED_FROM_STAGE, removedFromStage);
        stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler);
    }

    private function keyDownHandler(ev:KeyboardEvent):void
    {
        if (event.keyCode == Keyboard.DOWN)
        {
            select.y = 250;
        }
        if (event.keyCode == Keyboard.UP)
        {
            select.y = 200;
        }
    }

    private function removedFromStage(ev:Event):void
    {
        removeEventListener(Event.REMOVED_FROM_STAGE, removedFromStage);
        stage.removeEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler);
    }
}
}  
Was it helpful?

Solution

When you test your movie, you should be getting error messages like:

BG.as, Line 34 1120: Access of undefined property event.

The errors can give you a hint at what is going wrong. In this case, it's telling you that there is no property named "event". In your keyDownHandler function, you need to replace "event" with "ev" which is what you are naming your KeyboardEvent in the function declaration. So this should make your code work:

if (ev.keyCode == Keyboard.DOWN)
    {
        select.y = 250;
    }
if (ev.keyCode == Keyboard.UP)
    {
        select.y = 200;
}

Also, you should use parenthesis when creating object instances. Even though it still compiles, you should be writing:

public var select:Select = new Select();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top