javafx中的碰撞检测器(二维迷宫) [英] Collision detector in javafx (2d maze)
本文介绍了javafx中的碰撞检测器(二维迷宫)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何让我的球从屏幕上的物体上反弹?
How do I make my ball bounce off objects on the screen?
下图是球碰到障碍物后程序应该如何工作的一个很好的例子.
The picture below is a good example of how the program should be working once the ball runs into an obstacle.
我让球从墙上反弹,但剩下的就是让它也从物体上反弹.感谢您的帮助!
I made the ball bounce off the walls, but what's left is making it also bounce off objects. Thanks for the help!
这是源代码:
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() 方法做到这一点.
You could do that with the intersects() method.
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..
}
这篇关于javafx中的碰撞检测器(二维迷宫)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文