Arrays 部分工作数组/hitTestobject
我正在用数组尝试新事物,遇到了一些困难。我试图创建一个类的多个实例,并将它们放入一个数组中 我正在创建这样的实例:Arrays 部分工作数组/hitTestobject,arrays,actionscript-3,if-statement,Arrays,Actionscript 3,If Statement,我正在用数组尝试新事物,遇到了一些困难。我试图创建一个类的多个实例,并将它们放入一个数组中 我正在创建这样的实例: public function creatingitem(e:TimerEvent) { amtcreated = Math.ceil(Math.random() * 4); while (amtcreated >= 1) { amtcreated--; var i
public function creatingitem(e:TimerEvent)
{
amtcreated = Math.ceil(Math.random() * 4);
while (amtcreated >= 1)
{
amtcreated--;
var i:Number = Math.ceil(Math.random() * 3);
switch (i)
{
case 1 :
//Object1
objectnum = 1;
objectwei = 3;
r = new Board(objectnum,objectwei,stagw,stagh);
addChild(r);
fallingitem.push(r);
break;
case 2 :
//Object2
objectnum = 2;
objectwei = 4;
c = new Board(objectnum,objectwei,stagw,stagh);
addChild(c);
fallingitem.push(c);
break;
case 3 :
//Object3
objectnum = 3;
objectwei = 4;
l = new Board(objectnum,objectwei,stagw,stagh);
addChild(l);
fallingitem.push(l);
break;
default :
break;
}
}
}
创建这些球后,检查它们是否与主球碰撞:
public function hitcheck(e:Event)
{
for (var v:int = fallingitem.length - 1; v >= 0; v--)
{
if (ball.hitTestObject(fallingitem[v]))
{
trace(fallingitem[v]);
if (fallingitem[v] == r)
{
bonusscore += 100;
fallingitem[v].removeitem();
}
else if (fallingitem[v] == c)
{
bonusscore += 75;
fallingitem[v].removeitem();
}
else if (fallingitem[v] == l)
{
bonusscore += 75;
fallingitem[v].removeitem();
}
trace(bonusscore);
}
}
}
问题是,由于跟踪功能,我看到每个项目都被击中。并非所有实例都满足if条件。作为一个例子,我可以有2个r实例,当我击中这两个实例时,1个将通过并添加到分数,另一个将继续过去。紧跟在hitTestObject后面的跟踪告诉我这两个对象都被命中并注册,但我不确定为什么它不增加分数
谢谢,您不可能真正拥有2个r实例。创建实例时,如果碰巧创建了2个r,则第二个r=新板。。。语句覆盖引用,变量r引用第二个引用。这两个对象仍然存在,但变量只能引用其中一个对象,因此在执行检查时,将忽略以前设置为r但不再存在的对象
要解决这个问题,您可以将r、c和l转换为数组,并在创建实例时将其添加到相应的数组中。然后,您将使用r.indexofAllingItem[v]!=-1,如果对象在数组中,则返回true
另一种方法是,根据提供的代码,检查构造函数中objectnum设置的任何值,因为您是根据该值是在r、c还是l类别中进行设置的。不过,如果该物业是私人的或可能会发生变化,这将不起作用。我感谢您的帮助。我采用了第二种方法,即使用分配给它的objectnum的值。一旦我开始检查这个值,每个物体都会被击中。