简体   繁体   中英

AS3-Having a mouse click affect object in an array's timeline

I'm going crazy with this. I have a few bears on the stage and have listed them in an array. I want them to change their animation frame when clicked as long as they are not on the "down" animation frame to begin with. Below is the code. The problem occurs below the //check if they get hit line.

 //put the bears in an array
var bearsArray: Array = new Array();
for (var i=0; i<numChildren;i++) {
    if (getChildAt (i) is bear_mc) {
        bearsArray.push(getChildAt(i));
    }
}

//move them up and down
addEventListener(Event.ENTER_FRAME,upAndDown);
function upAndDown(event:Event){
    if (Math.random() < 0.02){
        var randomBear = Math.floor(Math.random() * 9);
            bearsArray[randomBear].gotoAndPlay("popup");
    }
}


//check if they get hit 
for (var j:int = 0; j < bearsArray.length; j++){
    bearsArray[j].addEventListener(MouseEvent.CLICK, hitBears);
}

function hitBears(e:MouseEvent){
    for (var k: int=0; k<numChildren; k++){
        if (bearsArray[k].currentFrame != "down"){
            trace("clicked"); 
            bearsArray[k].gotoAndPlay("surprised");
         }
    }
}

currentFrame returns an integer, not string. If you want to use string, you have to use currentFrameLabel or currentLabel .

EDIT: http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/display/MovieClip.html#currentLabel

If you want to control only one bear, remember that you don't need to cycle through them (actually that would serve no purpose as you would be checking every one of them). The better (and correct) approach would be this:

function hitBears(e:MouseEvent){
    var bear:MovieClip = e.currentTarget as MovieClip;
    if(bear.currentLabel != "down") { //or currentFrameLabel, depends how your mc is set up
        trace("clicked");
        bear.gotoAndPlay("surprised");
    }
}

I got it working by checking a hittest with the mouse instead of just checking the click. That works for some reason.

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