在这种情况下,有几种方法可以让您的代码变得 DRY(不要重复自己)。最好的方法是学习使用类。类是蓝图,专为这些场景而设计。
这是一个简单的类的例子,可以做你想做的事。在 Flash/Animate 中,依次转到 file、new、“ActionScript 3.0 Class” - 将其命名为 Crop。
在出现的文档中,应该有一些基本的样板代码。一切都应该包装在一个包裹中。这个包告诉 flash 在哪里可以找到这个类 - 所以这个例子,保持原样(只是package {)并将这个文件保存在与你的.fla 相同的文件夹中。所有函数都需要包装在类声明中,这应该根据您输入的名称(Crop)为您生成。接下来,您将看到一个与类同名的函数。这称为构造函数,每当您创建此类的新实例时,此函数就会运行。由于类是蓝图,因此您创建它们的实例是对象 - 然后这些对象获取您放入此类的所有代码。
所以,首先,你应该有这个:
package {
public class Crop {
public function Crop() {
// constructor code
}
}
}
让我们继续把你的代码放进去。详情见代码cmets:
package {
//imports should go here
import flash.display.MovieClip;
import flash.events.Event;
import flash.events.TimerEvent;
import flash.utils.Timer;
//lets make this class extend MovieClip - that means it will be a MovieClip in addition to everything else you add below
public class Crop extends MovieClip {
//instead of setInterval, use a timer - it's easier to manage and cleanup
//in class files, variables and functions have access modifiers, that's what the public and private words are about
//private means only this class can ever use the var/function
private var timer:Timer;
public function Crop() {
//initialize the timer - have it tick every 5 seconds, and repeat 4 times (to move you from frame 1 - 5)
timer = new Timer(5000, 4);
//listen for the TIMER event (which is the tick) and call the function 'grow' when the timer ticks
timer.addEventListener(TimerEvent.TIMER, grow);
}
//a function that starts the timer ticking
public function startGrowing():void {
timer.start();
}
//this function is called every timer tick.
private function grow(e:Event):void {
this.nextFrame(); //go to the next frame of your crop
}
}
}
保存文件。现在您有了这个类,您需要将它附加到您的库资产中,以便它们都获得此功能。
在库面板中,对于每个裁剪对象,右键单击(或在 Mac 上按住 ctrl+单击)并转到 properties。在属性中,单击advanced,并为其指定一个唯一的类名(例如Strawberry)。然后在基类字段中,输入Crop(我们刚刚创建的类)。对其他人重复。
现在在您的时间线上,当您希望作物开始生长时,您可以:
field1.startGrowing(); //assuming your instance `field1` is one of the crops that you assigned the base class `Crop` to
希望这为了解类的力量提供了一个切入点。您可以在其中添加更多功能,它会自动应用于您附加的所有作物。