gpt4 book ai didi

java - 即使声明为最终边界也会更新

转载 作者:行者123 更新时间:2023-12-01 11:52:27 24 4
gpt4 key购买 nike

我正在尝试制作一个带有球的程序,这些球(首先)在靠近屏幕边界时会弹起。

但是,当检查bounds.getmaxY()值时,我可以看到该值正在增加,并且我猜是因为if循环从未被使用过。

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();
}
});
}

最佳答案

您的 Bounds 变量根本没有改变,您只是每次都会获得它的一个新实例。

认为这里发生的情况是,您在查询 Pane 的边界之前更改了球的布局。 Pane 不断增大以适应球位置的变化。所以尝试一下

                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);

关于java - 即使声明为最终边界也会更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28697389/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com