Posts Tagged ‘tween

21
Nov
08

Tweening trouble

We had an odd problem in our new framework. We’ve centralized tween instantiation to a TweenManager class, a practical way to instantiate tweens without having to type the whole code shebang every time. It looked good, but after a while we noticed that sometimes the tween never finished properly. More research showed that it didn’t fire its TWEEN_END event. And it happened without any clear pattern. Some projects’ tweens worked ok, others not. Some worked one day, not the next. A debugging nightmare.

A bit of searching online showed that we weren’t the only ones experiencing this. The reason was that we assigned the tweens to variables within a function. As there was no other reference to it, it was eligible for garbage collection. And the flash player’s garbage collection happens when it wants. So sometimes the tween would be garbage collected before it reached the end and no event was fired.

It was fairly easy to fix – we now store references to the tween in a Dictionary and delete them on TWEEN_END

old code:

    var t:Tween = new Tween(targ, prop, options.ease, targ[prop] ,value, secs, true);
        //add listener for end of tween
        t.addEventListener(TweenEvent.MOTION_FINISH, function():void {
            t.dispatchEvent(new Event(TWEEN_END));
        });

revised code – we store options in a dictionary to be able to do different operations on end (like hide after fade out)

    if (_myTweens == null) _myTweens = new Dictionary();
    var t:Tween = new Tween(targ, prop, options.ease, targ[prop], value, secs, true);
    _myTweens[t] = options;
    //add listener for end of tween
    t.addEventListener(TweenEvent.MOTION_FINISH, onMotionFinish);

and clean up references with.

    private function onMotionFinish(e:Event):void {
       var t:Tween = Tween(e.target);
       var options:Object = _myTweens[e.target]
       if (options.hideAfter) t.obj.visible = false;
       delete _myTweens[t]
    }
Advertisements