Tweening global volume in flash

Just a quick reminder on how to shut up the master volume on a flash project. I like a smooth tween to the silence, so I’m using the TweenLite libraries.

private function volumeOff():void {
    var sf:SoundTransform = new SoundTransform();
    TweenLite.to(sf, 1, {volume:0, onUpdate:applySoundTransform, onUpdateParams:[sf]});
}

private function applySoundTransform(s:SoundTransform):void {
    SoundMixer.soundTransform = s;
}

The trick here is to tween the volume property of a throw-away SoundTransform object, and on each step of the Tween apply that object as the SoundMixer.soundTransform Object, with an helper function. Note that I’m not going to write the function inside the TweenLite’s partameter list, as it is gross and dirty.

Tweening the volume back to 1 is so easy that I’m not writing it, to not offend anyone.

Fading out and detaching

One class i really do like is TweenLite. I don’t really like the default tweening engine for a couple of reasons, but mainly because i have to save the tween object in a reference in my class, or the garbage collector could eat it (stopping the tweens in a unpredictable status).
TweenLite don’t require this (it exposes static functions, and keep internal references to the tweens) and permits me to specify functions to be called, not only handlers (which i know, may sound a little ActionScript 2.0, but in fact permits to call any funcion, and so avoiding one-line handlers).

One small example, (to be used inside a DisplayObjectContainer) is fading out a child, and detaching after. In one clear line:

TweenLite.to(mySprite, 1, {alpha:0, onComplete:removeChild, onCompleteParams:[mySprite], delay:0.5});

Let’s bring this a step further: we can easily apply this technique to all child of a given container:

package
{
    import flash.display.DisplayObject;
    import flash.display.Sprite;
    import gs.TweenLite;

    public class mySprite extends Sprite
    {
        public function mySprite()
        {
            super();
        }

        public override function removeChild(child:DisplayObject):DisplayObject {
            TweenLite.to(mySprite, 1, {alpha:0, onComplete:super.removeChild, onCompleteParams:[child], delay:0.5});
            return child;
        }

    }
}

So now all the time removeChild is called from outside, the child gently fade away, and then quietly removes himself.