Cat*_*Nip 0 flash actionscript-3
我是AS3的新手,我正在尝试通过在flash中进行实验来学习,通过使用非常简单的代码制作一个简单的2D农业游戏.
我已经在6个作品中创造了一个作物,这是一个动画片段,每个水果种植都有不同的框架.例如,第1-5帧是草莓种植,其中第5帧是准备采摘时,然后6-10是胡萝卜等
有没有办法让我这样做,以便我不必为下一个裁剪字段编写完全相同的代码,而是根据您点击的裁剪字段更改此代码中的变量?
这是代码的一个例子
if (field1.currentFrame == 1)
{
field1.nextFrame();
infoText.text = "You've watered the crop. Let's wait and see how it turns out!";
function plantStrawberry():void
{
field1.nextFrame();
if (field1.currentFrame == 5)
{
clearInterval(strawberryInterval);
}
}
var strawberryInterval = setInterval(plantStrawberry,5000);
}
Run Code Online (Sandbox Code Playgroud)
没有判断,如上所述,我对AS3很新,哈哈.
在这种情况下,有几种方法可以使用您的代码进行DRY(不要重复自己).最好的方法是学习使用课程.类是蓝图,是针对这些场景而制作的.
这是一个简单的类来做你想做的事情的例子.在Flash/Animate中,转到file,然后转到new,然后转到' ActionScript 3.0 Class ' - 给它命名Crop.
在出现的文档中,应该有一些基本的样板代码.一切都应该包装好.该软件包告诉flash在哪里找到这个类 - 所以这个例子,保持原样(只是package {)并将此文件保存在与您相同的文件夹中.fla.所有函数都需要包含在类声明中,这应该根据您放入的名称(Crop)生成.接下来,您将看到一个与该类名称相同的函数.这称为构造函数,只要您创建此类的新实例,此函数就会运行.由于类是蓝图,因此您创建它们的对象实例 - 这些对象然后获取您在此类中放置的所有代码.
所以,首先,你应该这样:
package {
public class Crop {
public function Crop() {
// constructor code
}
}
}
Run Code Online (Sandbox Code Playgroud)
让我们继续并将您的代码放入.有关详细信息,请参阅代码注释:
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
}
}
}
Run Code Online (Sandbox Code Playgroud)
保存文件.现在您已经拥有了这个类,您需要将它附加到您的库资源,以便它们都能获得此功能.
在库面板中,对于每个裁剪对象,右键单击(或在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
Run Code Online (Sandbox Code Playgroud)
希望这为进入阶级的力量提供了切入点.您可以在此功能中添加更多功能,它会自动应用于您附加到的所有作物.
| 归档时间: |
|
| 查看次数: |
68 次 |
| 最近记录: |