Java Reference
In-Depth Information
The intersects() method of the Node class shown here takes an argument of type Bounds , located in the
javafx.geometry package. It represents the rectangular bounds of a node, for example, the leftPaddle node shown
in the preceding code snippet. Notice that to get the position of the left paddle in the Group that contains it, we're
using the boundsInParent property that the leftPaddle (a Rectangle ) inherited from the Node class.
The net results of the intersect method invocations in the preceding snippet are as follows.
If the ball intersects with the bounds of the
rightWall or leftWall , the pongAnimation
Timeline is stopped and the game is initialized for the next play. Note that the rightWall and
left Wall nodes are one-pixel-wide rectangles on the left and right sides of the Scene . Take a
peek at Listing 2-8 to see where these are defined.
If the ball intersects with the bounds of the
bottomWall or topWall , the vertical direction of the
ball will be changed by negating the program's Boolean movingDown variable.
If the ball intersects with the bounds of the
leftPaddle or rightPaddle , the horizontal
direction of the ball will be changed by negating the program's Boolean movingRight variable.
for more information on boundsInParent and its related properties, layoutBounds and boundsInLocal ,
see the “Bounding rectangles” discussion at the beginning of the javafx.scene.Node class in the JavafX api docs.
for example, it is a common practice to find out the width or height of a node by using the expression
myNode.getLayoutBounds().getWidth() or myNode.getLayoutBounds().getHeight() .
Tip
Dragging a Node
As you experienced previously, the paddles of the ZenPong application may be dragged with the mouse. The
following snippet from Listing 2-8 shows how this capability is implemented in ZenPong for dragging the right paddle.
DoubleProperty rightPaddleY = new SimpleDoubleProperty();
...code omitted...
double rightPaddleDragStartY;
double rightPaddleDragAnchorY;
...code omitted...
void initialize() {
...code omitted...
rightPaddleY.setValue(235);
}
...code omitted...
rightPaddle = new Rectangle(470, 0, 10, 30);
rightPaddle.setFill(Color.LIGHTBLUE);
rightPaddle.setCursor(Cursor.CLOSED_HAND);
rightPaddle.setOnMousePressed(me -> {
initRightPaddleTranslateY = rightPaddle.getTranslateY();
rightPaddleDragAnchorY = me.getSceneY();
});
 
 
Search WWH ::




Custom Search