-
function checkBlockCollision() {
-
var block_width = $(".block").first().width();
-
var block_height = $(".block").first().height();
-
var ball_left = $("#ball").position().left;
35
var ball_top = $("#ball").position().top;
-
var blocks_left = false;
-
$(".block").each(function() {
-
if ($(this).css("visibility") == "visible") {
-
blocks_left = true;
40
var block_top = $(this).position().top;
-
var block_left = $(this).position().left;
-
var in_x = inXRange(ball_left, block_left, block_width);
-
var in_y = inYRange(ball_top, block_top, block_height);
-
if (in_x && in_y) {
45
Game.score += 10;
-
$(this).css("visibility", "hidden");
-
if (in_x) {
-
Game.ball.vy *= -1;
-
}
50
if (in_y) {
-
Game.ball.vx *= -1;
-
}
-
}
-
}
55
});
-
return blocks_left;
-
}
-
The
checkCollisions
function first checks whether the player has dropped the
ball. In this case we decrease the number of lives. Then we check whether
the player has lost all of his lives. If yes, we set the game’s state to
GameS-
tates.LOST
. Otherwise, we pause the game and set the ball and paddle positions
to their defaults.
ballDropped
compares the y-coordinate of the ball’s bottom with the y-coordinate
of the paddle’s bottom. If the ball’s bottom is greater, the ball has been
dropped.
Next we define two helper functions named
inXRange
and
inYRange
. They check
whether the ball overlaps with a block horizontally or vertically. We use these
functions in
checkBlockCollision
to see whether any visible block has been hit by
the ball.
Therefore, we need a few more jQuery methods. In line 33, we select all ele-
ments belonging to the class
block
using
$(".block")
. If you pass a selector to the
$
function that selects more than one element, the function automatically
returns a list of objects. We select the first object using the
first
method; then
report erratum • discuss
Creating the Game • 123
www.it-ebooks.info