Java Reference
In-Depth Information
Using the KeyFrame Action Event Handler
We're using a different technique in the timeline than demonstrated in the Metronome1 program earlier in the
chapter (see Figure
2-8
and Listing 2-5). Instead of interpolating two values over a period of time, we're using the
action event handler of the
KeyFrame
instance in our timeline. Take a look at the following snippet from Listing 2-8 to
see this technique in use.
pongAnimation = new Timeline(
new KeyFrame(new Duration(10.0), t -> {
checkForCollision();
int horzPixels = movingRight ? 1 : -1;
int vertPixels = movingDown ? 1 : -1;
centerX.setValue(centerX.getValue() + horzPixels);
centerY.setValue(centerY.getValue() + vertPixels);
})
);
pongAnimation.setCycleCount(Timeline.INDEFINITE);
As shown in the snippet, we use only one
KeyFrame
, and it has a very short time (10 milliseconds).
When a
KeyFrame
has an action event handler, the code in that handler—which in this case is once again a lambda
expression—is executed when the time for that
KeyFrame
is reached. Because the
cycleCount
of this timeline is
indefinite, the action event handler will be executed every 10 milliseconds. The code in this event handler does
two things:
checkForCollision()
, which is defined in this program, the purpose
of which is to see whether the ball has collided with either paddle or any of the walls
•
Calls a method named
•
Updates the properties in the model to which the position of the ball is bound, taking into
account the direction in which the ball is already moving
Using the Node
intersects()
Method to Detect Collisions
Take a look inside the
checkForCollision()
method in the following snippet from Listing 2-8 to see how we check for
collisions by detecting when two nodes intersect (share any of the same pixels).
void checkForCollision() {
if (ball.intersects(rightWall.getBoundsInLocal()) ||
ball.intersects(leftWall.getBoundsInLocal())) {
pongAnimation.stop();
initialize();
}
else if (ball.intersects(bottomWall.getBoundsInLocal()) ||
ball.intersects(topWall.getBoundsInLocal())) {
movingDown = !movingDown;
}
else if (ball.intersects(leftPaddle.getBoundsInParent()) && !movingRight) {
movingRight = !movingRight;
}
else if (ball.intersects(rightPaddle.getBoundsInParent()) && movingRight) {
movingRight = !movingRight;
}
}
Search WWH ::
Custom Search