Game Development Reference
In-Depth Information
cycle. A quick check against the left and right walls assures that you can't extend past them when controlling it. The
next update function will move the puck. Listing 4-15 shows the updatePuck function.
Listing 4-15. Updating the Puck
function updatePuck() {
var nextX = puck.x + puck.velX;
var nextY = puck.y + puck.velY;
if (nextX < leftWall) {
nextX = leftWall;
puck.velX *= -1;
}
else if (nextX > (rightWall - puck.width)) {
nextX = rightWall - puck.width;
puck.velX *= -1;
}
if (nextY < (ceiling)) {
nextY = ceiling;
puck.velY *= -1;
}
puck.nextX = nextX;
puck.nextY = nextY;
}
Using the puck's x and y velocity, a few temporary values are set up to determine its next location by adding
to its current point values. Similar to the paddle, collisions against the walls and ceiling are considered, and values
are adjusted appropriately to prevent the puck from moving out of bounds. In the case of the puck, and its constant
motion, a collision with a wall should reverse its x velocity, and its y velocity is reversed when hitting the ceiling.
Lastly, the puck is assigned its next x and y positions for the next render cycle.
Checking for Collisions
With the paddle controls set, and the puck in motion, some evaluations need to be made on what is about to happen
with these new positions, and what they might collide with. The next function in Listing 4-16 determines if the puck is
about to collide with the paddle.
Listing 4-16. Checking the Puck for a Collision with the Paddle
function checkPaddle () {
if (puck.velY > 0 && puck.isAlive && puck.nextY > (paddle.y -
paddle.height) && puck.nextX >= paddle.x && puck.nextX <=
(paddle.x + paddle.width)) {
puck.nextY = paddle.y - puck.height;
combo = 0;
paddleHits++;
puck.velY *= -1;
}
}
The puck's collision with the paddle is handled in the same way as the ceiling in that its y velocity is reversed
when hitting. Only the paddle is a moving target, so the collision detection is a bit more complicated. You need to
detect the x and y position of both the paddle and the puck to determine if they are about to intersect. This detection
 
Search WWH ::




Custom Search