我试图制作一个带有球的程序(首先)在关闭屏幕边框时反弹。
然而,当检查bounds.getmaxY()值时,我可以看到该值正在增加,因为if-loops永远不会被使用。
public class bouncyFX extends Application {
public static void main(String[] args) {
launch(args);
}
static Pane pane = new Pane();
@Override
public void start(final Stage primaryStage) {
Scene scene = new Scene(pane, 500, 200);
primaryStage.setScene(scene);
primaryStage.show();
pane.setOnMouseClicked(new EventHandler<MouseEvent>() {
public void handle(final MouseEvent event) {
final Ball ball = new Ball(event.getX(), event.getY(), 12, Color.AQUA);
ball.relocate(event.getX(), event.getY());
pane.getChildren().addAll(ball);
final Timeline loop = new Timeline(new KeyFrame(Duration.millis(10), new EventHandler<ActionEvent>() {
double deltaX = 2;
double deltaY = 2;
public void handle(final ActionEvent event) {
ball.setLayoutX(ball.getLayoutX() + deltaX);
ball.setLayoutY(ball.getLayoutY() + deltaY);
ball.Collision(deltaX, deltaY);
final Bounds bounds = pane.getBoundsInLocal();
final boolean atRightBorder = ball.getLayoutX() >= (bounds.getMaxX()-ball.getRadius());
final boolean atLeftBorder = ball.getLayoutX() <= (bounds.getMinX()+ball.getRadius());
final boolean atBottomBorder = ball.getLayoutY() >= (bounds.getMaxY()-ball.getRadius());
final boolean atTopBorder = ball.getLayoutY() <= (bounds.getMinY()+ball.getRadius());
if(atRightBorder || atLeftBorder)
deltaX *= -1;
if(atBottomBorder ||atTopBorder)
deltaY *= -1;
}
}));
loop.setCycleCount(Timeline.INDEFINITE);
loop.play();
}
});
}
答案 0 :(得分:1)
您的Bounds
变量根本没有变化,您每次都会得到一个新的实例。
我认为这里发生的事情是在查询窗格的边界之前更改球的布局。窗格正在增长,以适应球的位置变化。所以试试
final Bounds bounds = pane.getBoundsInLocal();
final boolean atRightBorder = ball.getLayoutX() + deltaX >= (bounds.getMaxX()-ball.getRadius());
final boolean atLeftBorder = ball.getLayoutX() + deltaX <= (bounds.getMinX()+ball.getRadius());
final boolean atBottomBorder = ball.getLayoutY() + deltaY >= (bounds.getMaxY()-ball.getRadius());
final boolean atTopBorder = ball.getLayoutY() + deltaY <= (bounds.getMinY()+ball.getRadius());
if(atRightBorder || atLeftBorder)
deltaX *= -1;
if(atBottomBorder ||atTopBorder)
deltaY *= -1;
ball.setLayoutX(ball.getLayoutX() + deltaX);
ball.setLayoutY(ball.getLayoutY() + deltaY);
// not sure what this line does, so you will need to put it where it makes sense:
ball.Collision(deltaX, deltaY);
答案 1 :(得分:0)
将值声明为final不会使对象不可变。它只是意味着对对象的引用不会改变 - 即每次引用bounds
时,您将获得相同的对象。分配后,无法将最终变量更改为指向另一个Bounds
对象。
答案 2 :(得分:0)
无法分配最终变量,但您可以更改它的属性,因为您没有将其变为不可变。
看一下关于定义不可变对象的this article。
在您的情况下,如果您可以访问Bounds对象,则可以使用此解决方案来实现它,但如果您无法修改Bounds对象以使其成为不可变,则需要为Bounds编写包装类。