我是AS3编程的新手,我第一次只在课堂上玩游戏。我的问题是我有一堆对象要启动,我不希望这在我的文档类中完成,但我不知道我是否可以使用另一个文件,以及如何在那里做所有这些。我的代码(文档类)是:
package {
import flash.display.MovieClip;
import flash.utils.getDefinitionByName;
public class Ingredient_game extends MovieClip {
//variables
var allFoods:Array;
//functions
public function Ingredient_game() {
// constructor code
//add an event listener to update position
addEventListener(Event.ENTER_FRAME, moveOnEscalator);
//initialise allFoods array
allFoods = new Array();
var mc1:MovieClip = new carrot();
var mc2:MovieClip = new lemon();
var mc3:MovieClip = new potato();
var mc4:MovieClip = new tomato();
var mc5:MovieClip = new cereals();
var mc6:MovieClip = new milk();
var mc7:MovieClip = new yoghurt();
var mc8:MovieClip = new apple();
var mc9:MovieClip = new bananas();
var mc10:MovieClip = new grapes();
var mc11:MovieClip = new orange();
var mc12:MovieClip = new pear();
var mc13:MovieClip = new strawberry();
var mc14:MovieClip = new watermelon();
allFoods.push(mc1);
allFoods.push(mc2);
allFoods.push(mc3);
allFoods.push(mc4);
allFoods.push(mc5);
allFoods.push(mc6);
allFoods.push(mc7);
allFoods.push(mc8);
allFoods.push(mc9);
allFoods.push(mc10);
allFoods.push(mc11);
allFoods.push(mc12);
allFoods.push(mc13);
allFoods.push(mc14);
for( var i = 0; i < allFoods.length; i++ ){
var newx:Number = 800+100*i;
allFoods[i].initialisePosition(newx, 500);
addChild(allFoods[i]);
}
}
function moveOnEscalator(e:Event):void{
for( var i = 0; i < allFoods.length; i++ ){
if( allFoods[i].x >= 0 ){
allFoods[i].x -= 5;
}
else{
allFoods[i].x = allFoods.length*100;
}
}
}
}
}
我需要的是将var mc1
到allFoods.push(mc14);
的代码放在另一个文件中!任何想法怎么??
答案 0 :(得分:1)
您可以创建一个实用程序类:
package
{
public class UtilityClass
{
public function buildMCs():Array
{
var result:Array = new Array();
result.push(new carrot());
result.push(new lemon());
result.push(new potato());
result.push(new tomato());
result.push(new cereals());
result.push(new milk());
result.push(new yoghurt());
result.push(new apple());
result.push(new bananas());
result.push(new grapes());
result.push(new orange());
result.push(new pear());
result.push(new strawberry());
result.push(new watermelon());
return result;
}
}
}
然后修改你的函数来调用buildMCs():
public function Ingredient_game()
{
addEventListener(Event.ENTER_FRAME, moveOnEscalator);
//create instance of utility class
var builder:UtilityClass = new UtilityClass();
//call buildMCs to populate array
allFoods = builder.buildMCs();
for (var i = 0; i < allFoods.length; i++ )
{
var newx:Number = 800+100*i;
allFoods[i].initialisePosition(newx, 500);
addChild(allFoods[i]);
}
}