Search code examples
actionscript-3children

Make all children do something...?


I'm wondering if there is an easy way to make all children simultaneously do something. In particular, I want everything on my stage to shake back and forth like an earthquake. It's a bit hard to single out everything on stage and add in the proper code because at a given time I don't always know the amount of children on stage.

Also, I'm not sure if it makes a difference, but sometimes when I addChild something, I don't go out of my way to add it to the stage...Like for a few buttons I'll do this.addChild(mybutton). I don't know if there's a way to access everything that has been addChilded even though I may not have added them directly to the stage? I'm pretty sure numChildren returns the value of the number of objects on screen, but I could be wrong...

I was thinking of doing something like

Inside my loop

if (numChildren >= 10 && nukeShakeTimer.currentCount == 0)
{
    nukeShakeTimer.start();
}
if (nukeShakeTimer.currentCount > 0)
{
    NukeShake();
}

NukeShake

    public function NukeShake():void
    {
        numberChildren = numChildren;
        trace(numberChildren);
        while (numberChildren > 0)
        {
            var tempObject:Object = getChildAt(numberChildren)
            if (nukeShakeTimer.currentCount % 2 == 1)
            {
                tempObject.x += 10;
            }
            if (nukeShakeTimer.currentCount % 2 == 0)
            {
                tempObject.x -= 10;
            }
            numberChildren -= 1;
        }
        if (nukeShakeTimer.currentCount > 30)
        {
            nukeShakeTimer.reset();
        }
    }

When I try this though, I get a runtime error for the line var tempObject:Object = getChildAt(numberChildren) and the error reads RangeError: Error #2006: The supplied index is out of bounds.

Also I feel like it may be possible to do this operation much faster without using a while loop, but maybe not. Help please, thanks!


Solution

  • If you want to address every child on the stage then you'll need to loop through them. As Cherniv says, changing your getChildAt call to use numberChildren-1 should resolve your error.

    It shouldn't matter whether or not everything is directly on the stage or not. Looping through the stage children will get you whatever container you added the objects to. Moving that container will move its children too. (Though you'll have to do more work if you need to move those children independently).

    But...
    In your specific case, it looks like you just want to shake everything on the screen together, in the same direction at the same rate. In this case, I would probably just add all my objects to a single container Sprite on the stage. Then, when you want to do a shake effect, you only need to move that one container object and everything moves together.