部分工作数组/ hitTestobject

时间:2012-06-15 03:47:36

标签: arrays actionscript-3 if-statement

我正在使用数组尝试新事物并遇到一些困难。我正在尝试创建1个类的多个实例并将它们放入数组中。

我正在创建这样的实例:

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条件。作为一个例子,我可以有两个“r”实例,当我同时击中两个时,将通过并添加到分数,另一个将继续过去。跟踪hitTestObject之后的跟踪向我显示两者都被命中并注册但我不确定为什么它不会添加分数。

谢谢,

1 个答案:

答案 0 :(得分:0)

您实际上不能拥有2个r个实例。当您创建实例时,如果您碰巧创建了2 r s,则第二个r = new Board...语句将覆盖引用,变量r将引用第二个r。这两个对象仍然存在,但变量只能引用其中一个,因此当您执行检查时,您忽略了之前设置为r但不再存在的对象。

要解决此问题,您可以将clArray转换为(r.indexOf(fallingitem[v]) != -1),无论何时创建实例,都要将其添加到相应的数组中。然后,您将使用true执行检查,如果对象在数组中,则返回objectnum

另一方面,基于提供的代码,将检查构造函数中设置的值{{1}},因为您根据它是否在r,c或l类别中设置该值。但是,如果财产是私有的或可能被更改,那将无效。

相关问题