我的目的是创建一款将球射向目标的游戏。不过,我更喜欢这个问题的一般答案。
Circle ball = new Circle(x1,y1,r);
Rectangle rect = new Rectangle(x2,y2,w,h);
Line path = new Line(x1,y1,x3,y3);
PathTransition pathTrans = new PathTransition(Duration.millis(t), path, ball);
pathTrans.play();
if (ball.getBoundsInParent().intersects(rect.getBoundsInParent()))
{
//foo
}
为什么程序没有捕获碰撞?
如果需要任何澄清,我很乐意提供更多信息。
最佳答案
您在开始动画后立即测试碰撞。除非两者在动画开始时相交,否则将测试为 false。
每当其中一个对象移动时,您都需要重复测试。最好的方法可能是创建一个绑定(bind)到两个 boundsInParent
属性的 BooleanBinding
,并监听其值的变化:
BooleanBinding collision = Bindings.createBooleanBinding( () ->
ball.getBoundsInParent().intersects(rect.getBoundsInParent()),
ball.boundsInParentProperty(),
rect.boundsInParentProperty());
collision.addListener((obs, wasColliding, isNowColliding) -> {
if (isNowColliding) {
// foo
}
});
(更简单的方法是向 ball.boundsInParentProperty()
添加一个监听器,向 rect.boundsInParentProperty()
添加一个监听器,并测试碰撞在每个监听器中。不过,这会重复代码,而且我认为效率会较低。)
关于java - 使用路径转换时对碰撞无响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27307658/