[英]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)。為什么我的球不動(根本),它停留在角落?
你實際上並沒有搬遷的球,當你移動。
請參見下面的示例,該示例將球重新定位在新的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變量,以免有所不同您最初編碼的解決方案中有太多內容。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.