Pages

Tuesday 30 September 2014

ActionScript 3.0 Duplicating Movieclips

You can use this code for creating a menu, duplicating a character etc. The below code snippet achieves just that.


// import all the necessary classes
import flash.display.MovieClip;
import flash.events.MouseEvent;
import fl.transitions.*;
import fl.transitions.Tween;
import fl.transitions.easing.*;
// end of importing classes

// define variables
// create a rect variable with Rect datatype. Draw a rectangle or any other graphic. Create a movieclip out of it

and in Symbol Properties from the library give a Class name as Rect with MovieClip as the base class
var rect:Rect = new Rect();

// Create a variable with datatype as mc
var mc:MovieClip;

// Create a Boolean isMenu variable assigning the value of true to it
var isMenu:Boolean = true;
// end of defining variables


// Animation functions. These functions will be used when duplicating and removing the duplicate movieclips
function animateMenu(whichClip:MovieClip)
{
// Alpha Tweening
var menuItemsFade:Tween = new Tween(whichClip,"alpha",Strong.easeInOut,0,1,1.2,true);
}


function animateMenuInv(whichClip:MovieClip)
{
// Alpha Tweening
var menuItemsFade:Tween = new Tween(whichClip,"alpha",Strong.easeInOut,1,0,1.2,true);
}



// Duplicate MovieClip function which duplicates the rect movieclip
function duplicateMc()
{
// Actual prototype duplicate movieclip function
MovieClip.prototype.duplicateMovieClip = function(obj:*, pName:String):Object
{
this[pName] = this.addChild(obj);
this[pName].name = pName;
return this[pName];
};

// The prototype duplicate movieclip is used in the for loop to duplicate the rect movieclip
for (var i:uint=0; i<5; i++)
{
mc = this.duplicateMovieClip(new Rect(), "mcRect_" + i);
mc.y = (i * (this.rect.height+7));
// animate the duplicated movieclips
animateMenu(mc);


// Click EventListeners added in each duplicate movieclips
this["mcRect_" + i].addEventListener(MouseEvent.CLICK, onRectClk);

function onRectClk()
{
trace("Yahoo!");
}
}

}


// This function is used to remove the duplicated movieclips
function removeMc()
{
for (var i:uint=0; i<5; i++)
{
// animate the removed movieclips
animateMenuInv(this["mcRect_" + i]);
this["mcRect_" + i].addEventListener(MouseEvent.CLICK, onRectClk1);

function onRectClk1()
{
this["mcRect_" + i].removeEventListener(MouseEvent.CLICK, onRectClk1);
}
}
}


// Create 2 buttons which calls the duplicateMc() and removeMc() functions

dupBtn.addEventListener(MouseEvent.CLICK, dupThis);

function dupThis(evt:MouseEvent):void
{
duplicateMc();
}

remBtn.addEventListener(MouseEvent.CLICK, dupRemove);

function dupRemove(evt:MouseEvent):void
{
removeMc();
}

No comments:

Post a Comment