Hardware Reference
In-Depth Information
Continued from previous page.
(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, ballSize);
}
void resetBall() {
// put the ball back in the center
xPos = width/2;
yPos = height/2;
}
8
You're almost ready to set the
ball in motion. But first, it's time to do
something with the reset and serve
buttons. Add another variable at the
beginning of the code (just before
the setup() method with all the other
variable declarations) to keep track of
whether the ball is in motion. Add two
more variables to keep score.
boolean ballInMotion = false; // whether the ball should be moving
int leftScore = 0;
int rightScore = 0;
 
Search WWH ::




Custom Search