AS3:单帧时间轴重复功能

AS3: repeating function in sigle frame timeline

我对动作脚本很陌生。我有单帧时间轴,并且有垂直移动影片剪辑的功能。我只想重复三遍。 代码有效,我只是不确定这是正确的方法还是太复杂了。

var pocet:Number = 0;

pruh.addEventListener(Event.ENTER_FRAME, fl_AnimateVertically);

function fl_AnimateVertically(event:Event)
{
if (pruh.y >= stage.stageHeight) {
    pocet++;
}
if (pruh.y < stage.stageHeight) {
pruh.y += 3;
}
else {
    pruh.y = 0 - pruh.y;
}
if (pocet == 3) {
    pruh.removeEventListener(Event.ENTER_FRAME, fl_AnimateVertically);
}
}

谢谢

试试这个

var pocet:Number = 0;

pruh.addEventListener(Event.ENTER_FRAME, fl_AnimateVertically);
var startY:int=pruh.y;
function fl_AnimateVertically(event:Event)
{
if (pruh.y >= stage.stageHeight) {
    pocet++;
 pruh.y=startY;
}
if (pruh.y < stage.stageHeight) {
pruh.y += 3;
}
else {
    pruh.y = 0 - pruh.y;
}
if (pocet ==3) {
    pruh.removeEventListener(Event.ENTER_FRAME, fl_AnimateVertically);
 
trace("done");
}
}

恭喜您实现了目标。

您的代码在可读性方面有待改进。您将 fl_AnimateVertically 作为描述性名称,但除此之外,很难弄清楚到底发生了什么。我的意思是肯定它会在 y 上加 3,这可能会导致移动,但了解确切的行为并非易事。

这就是为什么您想使用抽象或更多的自上而下的方法,因为它通常被称为.. 您现在正在做的是为坐标添加一个值,从而创建一个动画。您真正想要的是创建一个动画,而不是详细说明它的实际含义。

果然,以前人们用代码创建动画。这就是为什么您可以创建抽象意义上的动画:动画是对象的 属性 随着时间的变化。 In the realm of flash an animation is called a tween and there's a class doing exactly that..

让我们看看那里的示例代码:

var myTween:Tween = new Tween(myObject, "x", Elastic.easeOut, 0, 300, 3, true);

并将其应用到您的情况中。

var verticalAnimation:Tween = new Tween(pruh, "y", Elastic.easeOut, pruh.y, stage.stageHeight, 3, true);

您必须根据自己的喜好调整持续时间。我希望你看到这如何更容易阅读和维护,因为你指定了动画的属性,比如持续时间。还可以指定缓动,让动效更有趣

好的,这只是一个动画,但你想要 3 个,对吗? 更准确地说,当它完成时,你想再次做同样的动画。 你完全可以这样做:

var animationCount:uint = 0;
var verticalAnimation:Tween = new Tween(pruh, "y", Elastic.easeOut, pruh.y, stage.stageHeight, 3, true);

verticalAnimation.addEventListener(TweenEvent.MOTION_FINISH, onMotionFinish); // wait for the animation to be finished

function onMotionFinish(e:TweenEvent):void
{
    animationCount++; // add 1 to the counter

    if(animationCount >= 3)  // check how many times the animation finished so far
    {
        // if it was the last one, remove the listener
        verticalAnimation.removeEventListener(TweenEvent.MOTION_FINISH, onMotionFinish);
    }
    else
    {
        // otherwise rewind and start again
        verticalAnimation.rewind();
        verticalAnimation.start();
    }
}

Tween class 内置的其他库比这个库更强大。 The one from greensock is very popular and easy to use you can find the documentation for the flash version here