【发布时间】:2016-03-29 20:47:15
【问题描述】:
所以我正在编写一个程序,球在屏幕上弹跳,但是当我启动它时,球根本不动。我使用了 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 中它们在同一个包中),所以我使用第一个代码进行方法暗示,第二个文件是扩展到 Application 并具有整体启动程序的主要方法。所以我使用第二个来启动整个程序。
-
所以我猜第一个程序会让它移动,因为它有 Timeline animation = new Timeline 和 moveball() 方法。
-
嗯?你想让球在动画中移动,对吧?没有与动画相关的代码会导致球改变位置。
-
James_D 有一个good link on bouncing balls here Narinder。
标签: java ios animation javafx timeline