Game Development Reference
In-Depth Information
really only needs to run when the puck is moving downwards, so first check its velY value. The puck also has an
isAlive property that is set to false when it's beneath and beyond the reach of the paddle. This prevents you from
running its brick and paddle collision calculations during the time it travels beyond and below the stage.
Continue with the conditional by comparing the position and size values of both the puck and the paddle to see
if the rectangles intersect. If all conditions are met, then you know that the puck must be covering the paddle and a
collision is successfully detected. Updating the puck's nextY property to sit snuggly on top of the paddle, similar to the
walls and ceiling, gives it a much more natural look when bouncing up and away.
A few of the game variables need to be updated when the paddle hits the puck. The combo variable is used to
count consecutive brick hits before reaching the paddle again. This is used for the combo bonuses that are awarded
to the player. When the puck hits the paddle, this value is reset back to zero to restart the consecutive brick count. The
paddleHits variable is used to count the number of times the puck hit the paddle. This count is how you determine if
you should add a new level of bricks to the board. Finally, the y velocity is reversed, which will set the puck flying back
up towards the bricks. Figure 4-6 demonstrates the puck ricocheting off of the paddle.
Figure 4-6. The puck colliding with the paddle and bouncing away to the left
The next function (see Listing 4-17) handles the coolest part of the game, the brick busting! This function is one
of the most complex functions yet and consists of one giant loop. This loop checks all bricks in the game for a puck
collision, and a few conditionals are then written to factor in the bonus features.
Listing 4-17. Checking the Puck for Brick Collisions
function checkBricks() {
if(!puck.isAlive){
return;
}
var i, brick;
for (i = 0; i < bricks.length; i++) {
brick = bricks[i];
if (puck.nextY >= brick.y && puck.nextY <= (brick.y + brick.height)
&& puck.nextX >= brick.x && puck.nextX <= (brick.x +
brick.width)) {
score += brick.points;
combo++;
Search WWH ::




Custom Search