Monday, September 19, 2011

Flash reverts MovieClips to Original Negative Depth when moving to a Previous Frame

I have been working with Flash for over six years and there are still things that surprise me about Actionscript 2 - surprise but not delight!  This week, I was trying to create a new layer in between two existing ones on the stage, using code only.  I figured that I could create a new MovieClip and swapDepths to put it in the correct location.  Everything worked great except that my created MovieClip would disappear as I navigated to a previous frame.

It bothered me so much, that I created a very simple tester of the problem.  It has an actions layer and one layer with a thick red line drawn on it.  It has a text box that reports which of the four frames you are on.  It has a green button which goes to the next frame and a red button which goes to the previous frame.

On the first frame, I create an empty MovieClip with code, swap its depth with the stage MovieClip and draw a blue line on it.  Everything looks great as you go from Frame 1 to 2 to 3 to 4, but go back from Frame 3 to Frame 2 or from Frame 4 to Frame 3 and the blue line disappears.  If you trace the depth of the stage MovieClip, you see that Flash re-establishes it at its original depth when you navigate to the previous frame. Since your code-created MovieClip is at that depth, it gets wiped out. At least this is my current explanation.

Maybe you have a better theory and want to download the .fla to check it out.  Regardless, I currently think that there is no good way to simulate a timeline layer with code.

The code is:

stop();
trace("library_mc starts at depth: "+this.library_mc.getDepth());
this.library_mc.lineStyle(3,0xFF0000,100);
this.library_mc.moveTo(50,100);
this.library_mc.lineTo(200,150);
if (counter == undefined) counter = 0;
counter++;
trace("creating code_mc for the time: "+counter);
this.createEmptyMovieClip("code_mc", this.getNextHighestDepth());

this.code_mc.swapDepths(this.library_mc);

this.code_mc.lineStyle(1,0x0000FF,80);
this.code_mc.moveTo(200,50);
this.code_mc.lineTo(50, 150);

green_btn.onRelease = function(){
	this._parent.nextFrame();
}

red_btn.onRelease = function(){
	this._parent.prevFrame();
}
frame_txt.text = "I am on frame 1";
this.onEnterFrame = function(){
	frame_txt.text = "I am on frame " + _currentFrame;
	trace("library_mc depth "+this.library_mc.getDepth());
}