因此,我正在編寫一個程序,讓球在屏幕上彈跳,但是當我啓動它時,球根本無法移動。我用Timeline的動畫值,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)。爲什麼我的球不動(全部),它停留在角落裏?
您認爲哪些代碼會使其移動? –
好吧,他們都通過繼承(在NetBeans他們是在相同的包)連接,所以我使用的第一個代碼的方法含義和第二個文件是延伸到應用程序,並具有啓動程序的主要方法在一個整體。所以我使用第二個來啓動整個程序。 – NarinderRSharma
所以我想第一個程序會讓它移動,因爲它有Timeline animation = new Timeline和moveball()方法。 – NarinderRSharma