如何使用时间轴正确启动 JavaFX 动画



我正在尝试使用从本网站收集的代码来制作一个可以弹跳圆圈的应用程序。 当我现在单击时 - 它创建了一个圆圈,它似乎只是在原地振动并且不会从边界反弹。

这是解决我的问题的代码帽子谢谢大家

@FXML
private AnchorPane anchorPane;
@FXML
private Label ballCountLabel;
public int ballCount = 0;
public int mouseClick = 0;
Circle[] balls = new Circle[1000];
@Override
public void initialize(URL url, ResourceBundle rb) {
    pane.setBackground(new Background(new BackgroundFill(Color.WHITE, CornerRadii.EMPTY, Insets.EMPTY)));
    AnchorPane.setTopAnchor(pane, 0.0);
    AnchorPane.setLeftAnchor(pane, 0.0);
    AnchorPane.setTopAnchor(pane, 0.0);
    AnchorPane.setRightAnchor(pane, 0.0);
}
@FXML
private void mouseAddBall(MouseEvent event) throws Exception {
    balls[mouseClick] = new Circle(15, Color.BLANCHEDALMOND);
    balls[mouseClick].relocate(event.getSceneX(), event.getSceneY());
    pane.getChildren().add(balls[mouseClick]);
    ballCount++;
    ballCountLabel.setText("Ball Count: " + ballCount);
    addBallMovement(balls[mouseClick]);
    mouseClick++;
}
public void addBallMovement(Circle b){
    final Timeline loop = new Timeline(new KeyFrame(Duration.millis(10), new EventHandler<ActionEvent>() {
        double deltaX = 3;
        double deltaY = 3;
        @Override
        public void handle(ActionEvent t) {
            b.setLayoutX(b.getLayoutX() + deltaX);
            b.setLayoutY(b.getLayoutY() + deltaY);
            final Bounds bounds = pane.getBoundsInParent();
            final boolean atRightBorder = b.getLayoutX() >= (bounds.getMaxX() - b.getRadius());
            final boolean atLeftBorder = b.getLayoutX() <= (bounds.getMinX() + b.getRadius());
            final boolean atBottomBorder = b.getLayoutY() >= (bounds.getMaxY() - b.getRadius());
            final boolean atTopBorder = b.getLayoutY() <= (bounds.getMinY() + b.getRadius());
            if (atRightBorder || atLeftBorder) {
                deltaX *= -1;
            }
            if (atBottomBorder || atTopBorder) {
                deltaY *= -1;
            }
        }
    }));
    loop.setCycleCount(Timeline.INDEFINITE);
    loop.play();

我将Ball更改为Circle以测试您的代码。在向当前球添加移动之前,您将更改为 balls 数组中的下一个球。这可能给你一个NullPointerException.

改变

balls[mouseClick] = new Circle(event.getSceneX(), event.getSceneY(), 
Math.random() * 20);
pane.getChildren().add(balls[mouseClick]);
mouseClick++;
ballCount++;
ballCountLabel.setText("Ball Count: " + ballCount);
addBallMovement(balls[mouseClick]);  //<--You want to move the current ball. This code needs to be before mouseClick++

自:

balls[mouseClick] = new Circle(event.getSceneX(), event.getSceneY(), 
Math.random() * 20);
pane.getChildren().add(balls[mouseClick]);
addBallMovement(balls[mouseClick]);
mouseClick++;
ballCount++;
ballCountLabel.setText("Ball Count: " + ballCount);

最新更新