2014-12-05 16 views
1

我的目的是創建一個遊戲,在該遊戲中向目標發射球。不過,我更喜歡這個問題的一般答案。使用路徑轉換時對衝突沒有反應

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 
} 

爲什麼程序不能捕捉到碰撞?

如果需要澄清,我很樂意提供更多信息。

回答

2

您在開始動畫後立即測試碰撞。除非兩者在動畫開始處相交,否則將會測試錯誤。

任何時候只要有一個對象移動就需要重複測試。也許最好的方法是創建一個綁定到兩個boundsInParent性能BooleanBinding,也能聆聽到它的價值的變化:

BooleanBinding collision = Bindings.createBooleanBinding(() -> 
    ball.getBoundsInParent().intersects(rect.getBoundsInParent()), 
    ball.boundsInParentProperty(), 
    rect.boundsInParentProperty()); 

collision.addListener((obs, wasColliding, isNowColliding) -> { 
    if (isNowColliding) { 
     // foo 
    } 
}); 

(A比較幼稚的做法也只是增加一個監聽器ball.boundsInParentProperty()和監聽器rect.boundsInParentProperty(),並測試每個聽衆的碰撞情況,但重複的代碼,我認爲效率會降低。)

+0

順便提一句,這些形狀的邊界將是完全包含形狀的最小矩形。因此,如果圓形點擊角落上的矩形,您仍然會看到兩個形狀的可見部分之間的小間隙。您可能需要做大量的幾何才能獲得非常好的碰撞檢測功能。 – 2014-12-05 02:30:14