So I'm writing a program where the ball bounces around the screen but when i launch it, the ball doesn't move at all. I've used the animation value for Timeline, and dy and dx as my boundaries for radius across the screen.
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
}
}
}
This is my launch code:
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);
}
I took out the increase speed and decrease speed methods cause they seemed irrelevant (incase anyones wondering the speed was set at animation.setRate(animation.getRate() + 0.1). why is my ball not moving (at all), it stays in the corner?
You aren't actually relocating the ball when you move it.
See the sample below, which re-centers the ball at new x and y co-ordinate locations to move it.
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);
}
Note, you could do away with the separate x and y variables entirely, as their values are already represented via the centerX and centerY properties of the circle, but I've left your x and y variables in the above code so as not to differ too much from your originally coded solution.