
66 MAKING THINGS TALK
void animateBall() {
// if the ball is moving left:
if (xDirection < 0) {
// if the ball is to the left of the left paddle:
if ((xPos <= leftPaddleX)) {
// if the ball is in between the top and bottom
// of the left paddle:
if((leftPaddle - (paddleHeight/2) <= yPos) &&
(yPos <= leftPaddle + (paddleHeight /2))) {
// reverse the horizontal direction:
xDirection =-xDirection;
}
}
}
// if the ball is moving right:
else {
// if the ball is to the right of the right paddle:
if ((xPos >= ( rightPaddleX + ballSize/2))) {
// if the ball is in between the top and bottom
// of the right paddle:
if((rightPaddle - (paddleHeight/2) <=yPos) &&
(yPos <= rightPaddle + (paddleHeight /2))) {
// reverse the horizontal direction:
xDirection =-xDirection;
}
}
}
// if the ball goes off the screen left:
if (xPos < 0) {
resetBall();
}
// if the ball goes off the screen right:
if (xPos > width) {
resetBall();
}
// stop the ball going off the top or the bottom of the screen:
if ((yPos - ballSize/2 <= 0) || (yPos +ballSize/2 >=height)) {
// reverse the y direction of the ball:
yDirection = -yDirection;
}
// update the ball position:
xPos = xPos + xDirection;
yPos = yPos + yDirection;
// Draw the ball:
rect(xPos, yPos, ballSize,