0

在这个项目中,我试图跟踪一个球。如果球的颜色是灰色的,我希望它被一个正方形包围。我的问题是只有一个球被跟踪。我希望跟踪所有的灰球。

如果有人可以帮助我,我将不胜感激。

这是代码(从外部类调用 Ball 和 Box):

package {

import flash.display.Sprite;
import flash.events.Event;
import flash.geom.Point;

[SWF(frameRate='31')]

    public class Main extends Sprite
    {

        private var balls:Array;
        private var directions:Array = [new Point(-1,-1),new Point(0,-1),new Point(1,-1),
                                        new Point(-1,0),new Point(1,0),
                                        new Point(-1,1),new Point(0,1),new Point(1,1)
                                        ];

        private var ballNum: Number = 10;
        private var ball:Ball;
        private var ball2:Ball;
        private var box:Box;

        private var ay:Number = 5;
        private var gravity:Number = 6;
        private var bounce:Number = -0.9;

        public function Main()
        {
            init();
        }
        private function init():void
        {
            balls = new Array();

            for(var i:Number = 0; i < ballNum; i++)
            {
                ball = new Ball(Math.random() * 30);
                ball.x = Math.random() * stage.stageWidth;
                ball.y = Math.random() * stage.stageHeight;
                ball.direction = directions[Math.floor(Math.random()*directions.length)];
                addChild(ball);

                balls.push(ball);
            }

            box = new Box();
            addChild(box);

            addEventListener(Event.ENTER_FRAME, onEnterFrame);
        }

        private function onEnterFrame(event:Event):void
        {
            for(var i:int = 0; i < balls.length; i++)
            {
                balls[i].x += balls[i].direction.x;
                balls[i].y += balls[i].direction.y;
            }
            if(ball.color == 0xcccccc)
            {
                box.x = ball.x - box.width / 2;
                box.y = ball.y - box.height / 2;
            }
        }
    }
}
4

2 回答 2

2

你只有一个盒子,在 onEnterFrame 函数结束后,一个盒子只能有一个 x 和 y。

尝试这样的事情:

for (var i: int = 0; i < balls.length; i++) {
    balls[i].x += balls[i].direction.x;
    balls[i].y += balls[i].direction.y;

    if (balls[i].color == 0xcccccc) {
        box[i].x = balls[i].x - box[i].width / 2;
        box[i].y = balls[i].y - box[i].height / 2;
        //OR balls[i].box.visible=true;
    }
}
于 2013-08-30T20:10:02.487 回答
1

您需要在 for 循环中检查颜色以检查所有球:

for (var i: int = 0; i < balls.length; i++) {
    balls[i].x += balls[i].direction.x;
    balls[i].y += balls[i].direction.y;

    if (balls[i].color == 0xcccccc) {
        box.x = balls[i].x - box.width / 2;
        box.y = balls[i].y - box.height / 2;
    }
}
于 2013-08-30T18:59:42.077 回答