When the ball collides with a brick, we will use the same technique applied to the paddle to determine the path the ball will follow. When a brick is hit, we'll need to figure out which brick has been touched and then remove it from both the stage and the bricks group. Each brick removal will increment 100 points to the score. The score will be taken from the score
constant and added to the current score as text. To remove the bricks from the game, follow these steps:
gameLevel2()
function, create a function called removeBrick(event)
:function removeBrick(event)
if
statement. When checking for an event, we'll refer the event to the object name, "brick"
. This is the name we gave our brick
display object:if event.other.name == "brick" and ball.x + ball.width * 0.5 < event.other.x + event.other.width * 0.5 then vx = -vx elseif event.other.name == "brick" and ball.x + ball.width * 0.5 >= event.other.x + event.other.width * 0.5 then vx = vx end
if
statement to remove the brick from the scene when the ball collides with one. After a collision has been made, increase score
by 1. Initiate scoreNum
to take the value of the score and multiply it by scoreIncrease
:if event.other.name == "brick" then vy = vy * -1 event.other:removeSelf() event.other = nil bricks.numChildren = bricks.numChildren - 1 score = score + 1 scoreNum.text = score * scoreIncrease scoreNum.anchorX = 0 scoreNum.x = 54 end
if
statement that pops up the alert screen for a win condition and set the gameEvent
string to "win"
;if bricks.numChildren < 0 then alertScreen("YOU WIN!", "Continue") gameEvent = "win" end
end
:end
The following is a screenshot of the ball colliding with the paddle:
If you remember from the previous chapter, we gave the brick
objects a name called "brick"
.
When the ball hits the left-hand side of any of the individual bricks, it travels towards the left. When the ball hits the right-hand side of the bricks, it travels toward the right. The width of each object is taken as a whole to calculate the direction in which the ball travels.
When a brick is hit, the ball bounces upward (the y direction). After every collision the ball makes with a brick, the brick is removed from the scene and destroyed from the memory.
The bricks.numChildren – 1
statement subtracts the count from the total number of bricks it started out with originally. When a brick is removed, the score increments 100 points each time. The scoreNum
text object updates the score every time a brick is hit.
When all the bricks are gone, the alert screen pops up with a notification that the player has won the level. We also set gameEvent
equal to "win"
, which will be used in another function that will transition the event to a new scene.