简体   繁体   中英

(AS3) SAME ACTION ON DIFFERENT MOVIE CLIPS

I'm working on an interactive interface. On the timeline it contains a layer for action script, and a layer for the movie clips (around 12 on the stage). Each of the movie clips has got the same animation, and i applied the following code on one of them:

a.stop();

a.addEventListener(MouseEvent.MOUSE_DOWN, adown);
a.addEventListener(MouseEvent.MOUSE_UP, aup);

a.buttonMode = true;
a.mouseChildren = false;

function adown(e:MouseEvent):void 
{
    var mc:MovieClip = MovieClip(e.currentTarget);

    mc.removeEventListener(Event.ENTER_FRAME, rewind);

    mc.play();
    mc.addEventListener(Event.ENTER_FRAME, advance);
}

function aup(e:MouseEvent):void 
{
    var mc:MovieClip = MovieClip(e.currentTarget);

    mc.removeEventListener(Event.ENTER_FRAME, advance);

    mc.prevFrame();
    mc.addEventListener(Event.ENTER_FRAME, rewind);
}



function advance(e:Event):void 
{
    var mc:MovieClip = MovieClip(e.currentTarget);

    if (mc.currentFrame == mc.totalFrames)
    {
        mc.stop();
        mc.removeEventListener(Event.ENTER_FRAME, advance);
    }
}

function rewind(e:Event):void 
{
    var mc:MovieClip = MovieClip(e.currentTarget);

    if (mc.currentFrame == 1)
    {
        mc.stop();
        mc.removeEventListener(Event.ENTER_FRAME, rewind);
    }
    else
    {
        mc.prevFrame();
    }
}

It works perfectly on that one, but don't know what to do with the others. Does anybody know how to duplicate the code on the other movie clips? I want all of the movie clips to do the same action. Can anyone help me out? I really new to coding, sorry if it's a silly question. Thanks in advance!

A common way to avoid duplicating code for a group of objects that you want to behave in the same way is putting them all in an Array and iterating through it:

var movieArray:Array = new Array;

movieArray.push(a);
movieArray.push(b); //assuming you named your other movieclips b, c, etc.
movieArray.push(c);
//.
//.
//...until all of them are in there.

Then iterate through them with a for loop:

for (var i:uint = 0; i < movieArray.length; i++) {
    movieArray[i].stop();
    movieArray[i].addEventListener(MouseEvent.MOUSE_DOWN, adown);
    movieArray[i].addEventListener(MouseEvent.MOUSE_UP, aup);

    movieArray[i].buttonMode = true;
    movieArray[i].mouseChildren = false;
}

All your movieclips should now be behaving the same way as a did.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM