/home/caleb/ASDV-Java/Semester 3/Assignments/lab3_CalebFontenot/src/lab3_calebfontenot/BouncingBall.java |
package lab3_calebfontenot;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import static javafx.application.Application.launch;
import javafx.beans.property.DoubleProperty;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.util.Duration;
public class BouncingBall extends Pane {
final double radius = 20;
private double x = radius, y = radius;
private double dx = 1, dy = 1;
private Circle circle = new Circle(x, y, radius);
private Timeline animation;
public BouncingBall()
{
circle.setFill(Color.BROWN);
getChildren().add(circle);
animation = new Timeline(new KeyFrame(Duration.millis(1), new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent t)
{
moveBall();
}
})
);
animation.setRate(animation.getRate() * 20);
animation.setCycleCount(Timeline.INDEFINITE);
animation.play();
}
private void moveBall() {
if (x < radius || x > getWidth() - radius) {
dx *= -1;
}
if (y < radius || y > getHeight() - radius) {
dy *= -1;
}
x += dx;
y += dy;
circle.setCenterX(x);
circle.setCenterY(y);
}
public void play() {
animation.play();
}
public void pause() {
animation.pause();
}
public void increaseSpeed() {
animation.setRate(animation.getRate() * 1.5);
System.out.println(animation.getRate());
}
public void decreaseSpeed() {
animation.setRate(animation.getRate() * 1.5 > 0 ? animation.getRate() / 1.5 : 0);
System.out.println(animation.getRate());
}
public DoubleProperty rateProperty() {
return animation.rateProperty();
}
}