代码很好地说明了这个问题,我已经删除了所有不相关的内容。
游戏开始时创建2-4个亲属
function createInitialKinsmen()
{
for (var k:int = 1; k < 3 + Math.round(Math.random() * 2; k++)
{
if (k == 1)
{
createKinsmen(0);
trace ("player");
}
else
{
createKinsmen(1);
trace ("starting kinsmen");
}
}
}
亲属创建功能
function createKinsmen(arrivalTypeVar:int)
{
var newKinsmen = new kinsmen;
listPanel.kinsmenDivider.addChild(newKinsmen);
totalKinsmen++;
totalKinsmenAlive++;
newKinsmen.name = "kinsmen" + totalKinsmen;
newKinsmen.arrivalType = arrivalTypeVar;
}
亲属类
public class kinsmen extends MovieClip
{
var arrivalType:int;
function kinsmen()
{
trace(this.name);
if (this.arrivalType = 0)
{
trace("player");
}
if (this.arrivalType = 1)
{
trace("starting kinsmen");
}
}
}
输出应该是:
kinsmen1
player
player
kinsmen2
starting kinsmen
starting kinsmen
kinsmen3
starting kinsmen
starting kinsmen
kinsmen4
starting kinsmen
starting kinsmen
但取而代之的是:
kinsmen1
player
player
kinsmen2
player
starting kinsmen
kinsmen3
player
starting kinsmen
kinsmen4
player
starting kinsmen
这意味着arrivalType变量没有被传递。它似乎是可以传递的硬编码变量,因此目前我在亲属移动中有一个阿尔法为0的正方形,它的x位置决定了构造函数中rrivalType的值,但这肯定不是一个好的做法,有更好的方法吗?
我认为您只想修改kinsmen
类的构造函数,以接受arrivalType
和name
的参数。
您当前正在做的是构建一个新的kinsmen
对象,然后在该对象上设置arrivalType
和name
。因此,当构造函数代码运行时,arrivalType
是int
的默认值,即0。
在kinsmen
类中这样修改构造函数:
function kinsmen(arrivalType:int, name:String)
{
this.name = name;
this.arrivalType = arrivalType;
if (this.arrivalType == 0)
{
trace("player");
}
if (this.arrivalType == 1)
{
trace("starting kinsmen");
}
}
并修改createKinsmen()
函数,使其将arrivalType
的值传递给构造函数方法,而不是在创建对象后设置arrivalType
和name
:
function createKinsmen(arrivalTypeVar:int)
{
totalKinsmen++;
totalKinsmenAlive++;
var newKinsmen = new kinsmen(arrivalTypeVar, "kinsmen" + totalKinsmen);
listPanel.kinsmenDivider.addChild(newKinsmen);
}