gpt4 book ai didi

java - javafx 中的碰撞检测器(二维迷宫)

转载 作者:行者123 更新时间:2023-12-01 13:49:50 25 4
gpt4 key购买 nike

如何让我的球从屏幕上的物体上弹起?

下图是一个很好的例子,说明了当球遇到障碍物时程序应该如何工作。

enter image description here

我让球从墙壁上弹起,但剩下的就是让它也从物体上弹起。感谢您的帮助!

这是源代码:

public class 2DGAME extends Application {

public static Circle circle;
public static Pane canvas;
private long counter = 0;
double X = 0;
double Y = 0;

@Override
public void start(Stage primaryStage) {

canvas = new Pane();
Scene scene = new Scene(canvas, 800, 600);

primaryStage.setTitle("2D Ball Game");
primaryStage.setScene(scene);
primaryStage.show();

circle = new Circle(20, Color.BLUE);
circle.relocate(100, 100);

final Rectangle r = new Rectangle(20, 20, Color.DARKMAGENTA);
r.setLayoutX(400);
r.setLayoutY(300);

canvas.getChildren().addAll(circle);
canvas.getChildren().addAll(r);


Timeline loop = new Timeline(new KeyFrame(Duration.millis(5), new EventHandler<ActionEvent>() {

@Override
public void handle(ActionEvent t) {
if (counter++ % 5 == 0) {
// Moves the ball depending on the values of X and Y
circle.setLayoutX(circle.getLayoutX() + X);
circle.setLayoutY(circle.getLayoutY() + Y);

//Code to bounce off walls
final Bounds bounds = canvas.getBoundsInLocal();
boolean leftWall = circle.getLayoutX() <= (bounds.getMinX() + circle.getRadius());
boolean topWall = circle.getLayoutY() <= (bounds.getMinY() + circle.getRadius());
boolean rightWall = circle.getLayoutX() >= (bounds.getMaxX() - circle.getRadius());
boolean bottomWall = circle.getLayoutY() >= (bounds.getMaxY() - circle.getRadius());

//Bugged and not sure how to make it work
final Bounds rectangleBounds = r.getLayoutBounds();
boolean rectangle_left = circle.getLayoutX() <= (rectangleBounds.getMinX() + circle.getRadius());
boolean rectangle_right = circle.getLayoutX() >= (rectangleBounds.getMaxX() - circle.getRadius());


//If the bottom or top wall has been touched, the ball reverses direction.
if (bottomWall || topWall) {

Y = Y * -1;
}
// If the left or right wall has been touched, the ball reverses direction.
if (leftWall || rightWall) {
X = X * -1;
}

//Bugged code for boucning off obstacle object
if (rectangle_left || rectangle_right) {
// X = X * - 1;
}

}
}

}));

loop.setCycleCount(Timeline.INDEFINITE);
loop.play();
}

public static void main(String[] args) {
launch(args);
}

}

最佳答案

您可以使用 intersects() 方法来做到这一点。

boolean movingDown = true;

void checkforCollision(){
if(circle.intersects(bottomWall.getBoundsInLocal()){
movingDown = !movingDown;
// do something
}

else if(circle.intersects(rectangle.getBoundsInParent()) && !movingDown{
movingDown = !movingDown;
// do something
}
// etc..
}

关于java - javafx 中的碰撞检测器(二维迷宫),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20047379/

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