如何让我的弹跳球移动?

How do I make my bouncing ball move?

所以我正在编写一个程序,让球在屏幕上弹跳,但当我启动它时,球根本不动。我使用时间轴的动画值,dy 和 dx 作为我在屏幕上的半径边界。

public class BallPane extends Pane {

public final double radius = 5;
public double x = radius, y = radius;
public double dx = 1, dy = 1;
public Circle circle = new Circle(x, y, radius);
public Timeline animation;

public BallPane(){
//sets ball position
x += dx; 
y += dy; 
circle.setCenterX(x); 
circle.setCenterY(y);

circle.setFill(Color.BLACK);
getChildren().add(circle); 

// Create animation for moving the Ball
animation = new Timeline(
    new KeyFrame(Duration.millis(50), e -> moveBall() ));
animation.setCycleCount(Timeline.INDEFINITE);
animation.play();
}    

public void play(){
    animation.play();
}

public void pause(){
    animation.pause();
}

public DoubleProperty rateProperty(){
    return animation.rateProperty();
}

public void moveBall(){
// Check Boundaries
    if(x < radius || x > getWidth() - radius) {
        dx *= -1; //change Ball direction
    }
    if(y < radius|| y > getHeight() - radius) {
        dy *= -1; //change Ball direction
    }
}
}

这是我的启动代码:

    public class BounceBallControl extends Application {

@Override
public void start(Stage stage) {

    BallPane ballPane = new BallPane(); // creates the ball pane

    ballPane.setOnMousePressed( e -> ballPane.pause());
    ballPane.setOnMouseReleased( e -> ballPane.play());

    Scene scene = new Scene(ballPane, 300, 250);
    stage.setTitle("BounceBall!");
    stage.setScene(scene);
    stage.show();

    ballPane.requestFocus();
}
public static void main(String[] args){
   launch(args);
}

我去掉了增加速度和减少速度的方法,因为它们似乎无关紧要(以防有人想知道速度设置在 animation.setRate(animation.getRate() + 0.1)。为什么我的球不是移动(完全),它留在角落?

当你移动球时,你实际上并不是 relocating 球。

请参阅下面的示例,该示例将球重新置于新的 x 和 y 坐标位置以移动它。

public void moveBall() {
    x += dx;
    y += dy;

    // Check Boundaries
    if (x < radius || x > getWidth() - radius) {
        dx *= -1; //change Ball direction
    }
    if (y < radius || y > getHeight() - radius) {
        dy *= -1; //change Ball direction
    }

    circle.setCenterX(x);
    circle.setCenterY(y);
}

请注意,您可以完全取消单独的 x 和 y 变量,因为它们的值已经通过圆的 centerX 和 centerY 属性表示,但我在上面的代码中保留了您的 x 和 y 变量以免与您最初编码的解决方案相差太多。