如何在StackPane(在JavaFX中)的节点上实现冲突检测? [英] How to implement collision detection on nodes which are in StackPane (in JavaFX)?

查看:342
本文介绍了如何在StackPane(在JavaFX中)的节点上实现冲突检测?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试检查StackPane内部节点上的冲突检测。下面是我的代码:

I am trying to check collision detection on the nodes which are inside StackPane. Below is my code:

public void start(Stage primaryStage) throws Exception {
    StackPane pane = new StackPane();
    Scene scene = new Scene(pane,300,300,Color.GREEN);
    primaryStage.setScene(scene);       
    primaryStage.show();

    Rectangle  rect1 = new Rectangle(50, 50);
    rect1.setFill(Color.BLUE);
    Rectangle rect2 = new Rectangle(50, 50);         

    pane.getChildren().add(rect1);
    pane.getChildren().add(rect2);

    TranslateTransition translateTransitionEnemyCar = new TranslateTransition();
    translateTransitionEnemyCar.setDuration(Duration.millis(2000));
    translateTransitionEnemyCar.setNode(rect2);
    translateTransitionEnemyCar.setFromY(-150);
    translateTransitionEnemyCar.setToY(150);
    translateTransitionEnemyCar.setAutoReverse(true);
    translateTransitionEnemyCar.setCycleCount(Timeline.INDEFINITE);
    translateTransitionEnemyCar.play();             
    checkCollision(pane,rect1,rect2);       
}

//Collision Detection
 void checkCollision(StackPane pane, final Rectangle rect1, Rectangle rect2){   

     rect2.boundsInParentProperty().addListener(new ChangeListener<Bounds>() {
        @Override
        public void changed(ObservableValue<? extends Bounds> arg0,Bounds oldValue, Bounds newValue) {
            if(rect1.intersects(newValue)){
                System.out.println("Collide ============= Collide");
            }
        }
    });
 }
}

如果我使用AnchorPane,碰撞检测功能正常。但是使用StackPane我无法实现它。我想这是因为堆栈窗格的坐标系统(如果我错了就纠正我)。

Here the collision detection is working if I use AnchorPane. But with StackPane I am not able to achieve it. I guess it is because of the co-ordinate system of the stack pane (Correct me if I am wrong).

所以请帮我实现碰撞检测以上两个矩形。如果我想改变节点的坐标,请提供一些建议(如果你知道的话)在StackPane内的节点上实现这种碰撞检测。

So please help me out to achieve collision detection of the above two rectangles. Also please provide some suggestion (if you know) to implement such collision detection on nodes inside StackPane if I want to change the the co-ordinate of the nodes.

推荐答案

在测试条件下,将一个矩形的局部边界与另一个矩形的父节点的边界进行比较。您想要比较相同的边界类型。

In your test condition you compare the local bounds of one rectangle with the bounds in parent of the other rectangle. You want to compare the same bounds types.

所以更改:

rect1.intersects(newValue)

收件人:

rect1.getBoundsInParent().intersects(newValue)

为了更好地理解边界类型,你可能会想玩这个十字路口演示应用程序。

To understand bounds types better, you might want to play with this intersection demo application.

这篇关于如何在StackPane(在JavaFX中)的节点上实现冲突检测?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆