重复和重置循环

Repeat & Reset Loop

我想知道是否可以重复和重置循环。我正在使用 TweenLite 创建 3 张图片的幻灯片动画。每个之间有 3 秒的延迟。

6 秒后,我希望这个循环自己重复,这样我就有了幻灯片。任何建议,因为到目前为止我已经结束了无限循环导致它崩溃。

var clips:Array = [image, image2, image3];
var i = 0;

while ( i < 4) {
    var timer = i;
    TweenLite.to(clips[i], 6, {x:300, ease:Linear.easeNone,delay:timer*3});
    i++;
}

循环将 运行 与程序一样快,同步地锁定线程直到完成。这意味着任何基于时间的东西都不应该在循环中(因为循环没有时间概念)

我建议使用 TweenLite 内置的 complete 回调。

//create a var to store which item is current
var curIndex:int = 0;

//animate the current item
next();

function next(delay:Number = 0):void {
    //when the tween is complete, call the 'tweenComplete` function and pass the curIndex as a parameter
    TweenLite.to(clips[curIndex], 2, {x: 300, ease:Linear.easeNone, onComplete: tweenComplete, onCompleteParams: [curIndex], delay: delay);

    //increment the current index, reset to 0 if out of range
    curIndex++;
    if(curIndex >= clips.length){
        curIndex = 0;
    }
}

function tweenComplete(index){
    next(); //animate the next item

    //get the previous item and reset it's x position (now that this new item is in place) 
    index--;

    //if index was 0, get the highest index instead
    if(index < 0) index = clips.length - 1;

    clips[index].x = -300; //whatever your default x value is.
}

将代码放在函数中:

function startAnimations():void
{
    for(var i:uint = 0; i < 4; ++i)
    {
        TweenLite.to(clips[i], 6, {x:300, ease:Linear.easeNone, delay:timer*3});
    }
}

然后每当你想再次启动动画时调用该函数:

startAnimations();

要间隔一段时间执行此操作,请使用 Timer

var timer:Tiemr = new Timer(6000); //6000 ms = 6s
timer.addEventListener(TimerEvent.TIMER, startAnimations);
timer.start();

这需要将函数的签名更改为

function startAnimations(e:TimerEvent = null):void

您应该考虑使用 TimeLineLite。这是 Greensock 的一个很棒的动画排序插件,内置了动画排序、反转、暂停、重新启动等方法。

为了达到你想要的效果,你可以使用类似这样的东西(显然根据你的需要调整 values/code):

import com.greensock.TimelineLite;
private var timeLine:TimelineLite;
private var clips:Array;

private function animate():void
{
    clips = [image1, image2, image3];
    timeLine = new TimelineLite({onComplete:reset});
    for (var i:uint = 0; i < clips.length; i++)
    {
        timeLine.to(clips[i], 3, {x:400, ease:Linear.easeNone, delay:i*3});
    }
    timeLine.play();
}

protected function reset():void
{
    timeLine.restart(true);
}

注意 TimeLineLite 的 onComplete 方法。这将在补间完成时调用。

希望这能解决您的问题。

编辑:更新到最新的插件代码。

使用 TweenMax:(即如果你能负担得起一些额外的 KB)

var clips:Array = [image, image2, image3];
var timeline = new TimelineMax({ repeat: -1 });
timeline.staggerTo(clips, 6, { x: 300, ease: Linear.easeNone }, 3);