views:

260

answers:

2

The problem I've encountered is that I am using a keyboardEventListener to make a movieclip run around. As I'm a college student, I'm creating this for an assignment but we are forced to use as3 classes.

When I run the code in the maintimeline, there is no problem. But when I try to access it from another class (with an 'Export for ActionScript' on the movieclip in question) I get an error he can't address the stage.

this.stage.addEventListener(KeyboardEvent.KEY_DOWN, dostuff);

+1  A: 

A class in AS3 is not on the stage until you actually place it there. As a result, "this.stage" will be null at compile time. You can get around this problem by using the ADDED_TO_STAGE event to delay binding your listeners until the time is right.

public function MyClass(){
    this.addEventListener(Event.ADDED_TO_STAGE, addedToStageHandler);
}

private function addedToStageHandler(e:Event):void{
    this.stage.addEventListener(KeyboardEvent.KEY_DOWN, dostuff);
}
Greg W
Alrgiht! I've solved the stage problem. I still get a few errors though. I'm getting the error that he can't find the keyboard and every error is located on the following kind of code "if (evt.keyCode == Keyboard.RIGHT){ //stuff}"the error is the following:"1120: Access of undefined property Keyboard."already thanks for solving the stage thing! Searched Google down for it but couldn't find anything relevant!
Graphithy
@Graphithy if you have a different question, ask a new question on stackoverflow instead of asking it in a comment.
davr
A: 

"1120: Access of undefined property Keyboard. There's your answer. You haven't defined the keyboard properties. Which means you haven't imported to the package.

should look something like this:

 import flash.display.*;
 import flash.events.*;
 import flash.ui.*; 

Advice: have a deeper look into importing. try using flash builder, its much better for beginners and auto import classes so u dont need to memorize everything.

Eddy Ferreira