For this simple case we can easily use a "local collision listener" on the ball to both detect the collision and run some function to destroy the brick. Every collision is either in the "began" phase which occurs at the moment of collision or in the "ended" phase which occurs just as the objects stop colliding.
Build the collision system in three steps.
- Write a function that contains what you want to occur on collision.
-- Collision behavior for the ball
local function ballCollided(self, event)
body = event.other
--Allow the ball to rebound before we destroy any objects
if(event.phase == "ended") then
-- Destroy any bricks that we collide with
if body.type == "brick" then -- The field "type" was added to the brick. See full source.
body:removeSelf()
end
end
end - Tell your display object to use this function for collisions:
ball.collision = ballCollided
- Let your display object know that it should listen for its own collision events:
ball:addEventListener("collision", ball)
Now the brick vanishes just as the ball hits it and rebounds. Next creating a scene full of bricks...