R – Custom (simple) AS3 Class code not executing entirely

actionscriptactionscript-3flash

This problem is probably very simple to solve but it is not clear to me. It may simply be that I am doing something incorrectly. I have studied OOP and AS3 for quite a few hours so I am familiar with the concepts but not the flow. This is a project that I put together in order to reinforce what I have been studying.

The goal here is to load an instance of a pre-created movieclip to the stage from the library then execute a positioning function in the FLA's timeframe ActionScript and execute a function from within the AS files's class ActionScript to both a resize the movieclip and output a trace.

I have two files:
smileface.fla
smileface.as

In smileface.fla, I have a MovieClip object that resides in my Library. It has the following relevant properties…

Name: faceInst
Class: smileface
Base Class: null

I have one frame (keyframe) and it contains the following ActionScript:

var faceInst:smileface = new smileface();
this.addChild(faceInst);
faceInst.x = stage.stageWidth/2;
faceInst.y = stage.stageHeight/2;

In my smileface.as file I have the following code:

package {
    import flash.display.MovieClip;
    import flash.display.Stage;
    public class smileface extends MovieClip {
        public function smileFunction() {
            this.width = stage.stageWidth/5;
            this.height = stage.stageHeight/5;
            trace("Done!");
        }
    }
}

I expect (with no grounds to do so) that after the movieclip object is loaded that it will resize per the specification and then the trace will be output.

However, what happens instead is that the face is displayed on the stage, centered, but is not resized and the trace is not output at all.

Best Answer

If you are wanting this as the constructor it needs to have the same name as the file, smileface rather than smilefunction

as you are creating the instance before you are adding it to stage, the call for the stage width in the constructor is going to be null. you should move it onto an added to frame event listener:

package {
    import flash.display.MovieClip;
    import flash.display.Stage;
    public class smileface extends MovieClip {
        public function smileFace() {
        addEventListener(Event.ADDED_TO_STAGE, init);
        }

    public function init(ev:Event){
            this.width = stage.stageWidth/5;
            this.height = stage.stageHeight/5;
            trace("Done!");
        }
    }
}
Related Topic