Reputation: 281
var i:Number;
for (i=0;i<6;i++)
{
var brick:Sprite=new Sprite();
brick.graphics.beginFill(0x02589E);
brick.graphics.drawRect(0,0,70,7);
brick.graphics.endFill();
brick.y=10;
brick.x=12+(80*i);
addChild(brick);
}
addEventListener(Event.ENTER_FRAME,destroy);
var ball:Sprite=new Sprite();
ball.graphics.beginFill(0xff0000);
ball.graphics.drawCircle(0,0,7);
ball.graphics.endFill();
ball.x=200;
ball.y=230;
addChild(ball);
.......some code for ball moving.......
function destroy(e:Event):void
{
if(ball.hitTestObject(brick)){
removeChild(brick);
}
}
When the ball collide with the brick,only the last brick remove.But I want to remove all the brick separately if the ball collide with the brick.
Upvotes: 0
Views: 84
Reputation: 39458
Currently, brick
is referring to the last instance created in your for loop. What you need to do is store these objects in an array, loop through that array, and check for a collision between each individual brick within that array.
It might look something like this:
// Define the array.
var bricks:Array = [];
// Create bricks.
for(var i:int = 0; i < 6; i++)
{
var brick:Sprite = new Sprite();
brick.y = 10;
brick.x = 12 + (80 * i);
brick.graphics.beginFill(0x02589E);
brick.graphics.drawRect(0, 0, 70, 7);
brick.graphics.endFill();
addChild(brick);
bricks.push(brick);
}
And then your collision checking code:
function destroy(e:Event):void
{
for each(var brick:Sprite in bricks)
{
if(ball.hitTestObject(brick))
{
removeChild(brick);
}
}
}
Upvotes: 2
Reputation: 735
Here brick
only refers to a single object. Add all your bricks to an array and then loop through them in your destroy function.
Upvotes: 0