Eventually, we set the ball’s position to the new values in line 30.
Moving the paddle is similar, but it depends on the current state of the game
controller. If the player wants the paddle to move left, we subtract the paddle’s
current speed from the paddle’s x-coordinate. We also make sure that the
paddle doesn’t leave the screen. Movement to the right works nearly the same.
We only have to add the paddle’s current speed.
A difficult problem in video games is collision detection. You’ve probably
played a game or two and yelled “No, that thing didn’t hit me!” or “I’m sure I
killed that alien first!” In most cases inexact collision detection is the cause
of your frustration.
Even for our simple game, exact collision detections aren’t easy. The blocks
have rounded corners, so checking whether the ball overlaps one of the corners
or has actually touched the block isn’t trivial. For a good game experience
this isn’t necessary, so I’ve simplified the collision detection.
BrowserGame/Arduinoid/js/arduinoid.js
function checkCollisions() {
Line 1
if (ballDropped()) {
-
Game.lives = Game.lives - 1;
-
if (Game.lives == 0) {
-
Game.state = GameStates.LOST;
5
} else {
-
Game.state = GameStates.PAUSED;
-
resetMovingObjects();
-
}
-
}
10
if (!checkBlockCollision()) {
-
Game.state = GameStates.WON;
-
}
-
}
-
15
function ballDropped() {
-
var ball_y = $("#ball").position().top;
-
var paddle_y = $("#paddle").position().top;
-
return ball_y + Game.ball.diameter > paddle_y + Game.paddle.height;
-
}
20
-
function inXRange(ball_left, block_left, block_width) {
-
return (ball_left + Game.ball.diameter >= block_left) &&
-
(ball_left <= block_left + block_width);
-
}
25
-
function inYRange(ball_top, block_top, block_height) {
-
return (ball_top + Game.ball.diameter >= block_top) &&
-
(ball_top <= block_top + block_height);
-
}
30
Chapter 7. Writing a Game for the Motion-Sensing Game Controller • 122
report erratum • discuss
www.it-ebooks.info