views:

63

answers:

2

I'm trying to figure out an easy way to fade 4 (or any number) images and loop it so the last image fades in with the first image. I threw something together which is pretty horrible, and doesn't even fade the last image into the first. The code is included below for you to laugh at.

Any idea how I could improve this?

function beginTween():void
{
TweenMax.to(bg01, 2, { alpha:1 });
TweenMax.to(bg01, 2, { alpha:0, delay:20 });

TweenMax.to(bg02, 2, { alpha:1, delay:20 });
TweenMax.to(bg02, 2, { alpha:0, delay:25 });

TweenMax.to(bg03, 2, { alpha:1, delay:25 });
TweenMax.to(bg03, 2, { alpha:0, delay:30 });

TweenMax.to(bg04, 2, { alpha:1, delay:30 });
TweenMax.to(bg04, 2, { alpha:0, delay:35 });

TweenMax.to(bg05, 2, { alpha:1, delay:35 });
TweenMax.to(bg05, 0.5, { alpha:0, delay:40, onComplete:beginTween });
}

beginTween();  
A: 

You can do it with a loop like this.

function beginTween():void {

    var bgs:Array = [bg01, bg02, bg03, bg04];
    var i:int = 0;

    for each(var bg:Sprite in bgs) {
        TweenMax.to(bg, 2, {alpha: 1, delay: i == 0 ? 0 : 15 + 5 * i});
        TweenMax.to(bg, i == 4 ? 0.5 : 2, {alpha: 0, delay: 20 + 5 * i, onComplete: i == 4 ? beginTween : null});
        i++;
    }
}

But I actually prefer your method. It's cleaner and easier to understand. Sometimes a little duplication is ok.

Sam
A: 

This is not tested, but is definitely the right idea.

var count:int;
var currentImage:Bitmap;
var images:Array = [];
images.push(img);
images.push(img);
images.push(img);
//etc...

function transitionImages():void {
    TweenMax.to(currentImage, 2, { alpha:0 });
    currentImage = images[++count % images.length];
    TweenMax.to(currentImage, 2, { alpha:1, onComplete:transitionImages });
}
Tyler Egeto
Very cool, I like this. However, I keep getting the following error when I implement it (this error loops): TypeError: Error #1009: Cannot access a property or method of a null object reference. at com.greensock::TweenLite/init() at com.greensock::TweenMax/init() at com.greensock::TweenMax/renderTime() at com.greensock.core::SimpleTimeline/renderTime() at com.greensock::TweenLite$/updateAll()
dallen33
I should add that it works, but that's the error the Flash IDE output shows.
dallen33
Like I said, not tested. But this is probably because currentImage is null at the start, set it equal to the first image before you call it the first time, or add a if(currentImage) check
Tyler Egeto
Perfect, that worked and makes sense. Thank you for your help!
dallen33
No problem, I love refactoring code!
Tyler Egeto