if (next_x_pos >= paddle_x &&
-
next_x_pos <= paddle_x + Game.paddle.width)
-
{
-
Game.ball.vy *= -1;
25
next_y_pos = paddle_y - Game.ball.diameter;
-
}
-
}
-
-
$("#ball").css({ "left" : next_x_pos, "top" : next_y_pos });
30
}
-
-
function movePaddle() {
-
if (Game.controller.moveLeft) {
-
var paddle_x = $("#paddle").position().left;
35
if (paddle_x - Game.paddle.speed >= 0) {
-
$("#paddle").css("left", paddle_x - Game.paddle.speed);
-
} else {
-
$("#paddle").css("left", 0);
-
}
40
}
-
-
if (Game.controller.moveRight) {
-
var paddle_x = $("#paddle").position().left;
-
var next_pos = paddle_x + Game.paddle.width + Game.paddle.speed;
45
if (next_pos < Game.playfield.width) {
-
$("#paddle").css("left", paddle_x + Game.paddle.speed);
-
}
-
}
-
}
50
The most useful jQuery method when moving objects is
position
. It returns an
object that contains an HTML element’s current
left
and
top
attributes. In CSS,
these attributes specify an object’s x- and y-coordinates on the screen. In
lines 2 to 4 of the
moveBall
function, we use the
position
function to determine
the ball’s current screen coordinates. In the following two lines, we calculate
the ball’s new position by adding the current velocities for both directions.
After that, we check whether the ball’s new position would be out of the screen.
If yes, we clip the coordinates to the screen’s boundaries. In lines 8 to 14, we
make sure that the ball’s x-coordinate is greater than zero and less than the
playfield’s width. If the ball hits the left or right boundary of the playfield, we
multiply
vx
by -1, so it changes its direction.
Nearly the same happens in lines 16 to 28 for the ball’s y-coordinate. When-
ever the ball hits the top of the playfield, we multiply
vy
by -1. The playfield
has no bottom boundary, but we have to check whether the ball would hit
the paddle. If it does, we invert
vy
, too.
report erratum • discuss
Creating the Game • 121
www.it-ebooks.info