2016-03-29 53 views
0

因此,我正在編寫一個程序,讓球在屏幕上彈跳,但是當我啓動它時,球根本無法移動。我用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)。爲什麼我的球不動(全部),它停留在角落裏?

+2

您認爲哪些代碼會使其移動? –

+0

好吧,他們都通過繼承(在NetBeans他們是在相同的包)連接,所以我使用的第一個代碼的方法含義和第二個文件是延伸到應用程序,並具有啓動程序的主要方法在一個整體。所以我使用第二個來啓動整個程序。 – NarinderRSharma

+0

所以我想第一個程序會讓它移動,因爲它有Timeline animation = new Timeline和moveball()方法。 – NarinderRSharma

回答

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的以上代碼,以免與您最初編碼的解決方案有太大的不同。

+0

哦,看看我所做的是我已經重定位了circle.setCenterY()和X()在程序的頂部沒有想到它會有所作爲,我沒有意識到它是在MoveBall()方法必須確保我檢查我的「{}」權利。所以如果我想讓球速度更快,我會把我的Duration.millis()對嗎?其實從來沒有意識到我只是意識到我會使用我的increaseSpeed方法來做到這一點。thanx – NarinderRSharma

+1

不,改變時間線的持續時間對你來說不是一個好的解決方案(你會得到波濤洶涌的動畫或缺乏細粒度動態控制球的速度,除非你也使用內插鍵值)。也許你應該問一個關於改變移動速度的最佳方式的新問題。 – jewelsea

+0

哦,我做了一個例子,我的書在一週或兩週之後用一個球繞着一個圓(橢圓)旋轉,它會在曲線上減速,所以我用setInterpolator(Interpolator.LINEAR);我猜這就是你所說的內插鍵的意思。但速度會更有利於我,對嗎? – NarinderRSharma