2015-01-17 29 views
2

我試圖檢測形狀(XAML),在我的情況下矩形,擊中另一個矩形。Windows Phone 8:C#XAML如何檢測形狀碰撞

我試着搜索了一個小時,仍然沒有找到幫助我解決問題的東西。我也沒有使用XNA,所以請不要爲我提供XNA解決方案。

就在碰撞的示例:

enter image description here

在此先感謝!

+0

你到目前爲止嘗試了什麼? – khlr

回答

1

如果您知道這些矩形中的每一個的LocationSize。碰撞代碼非常簡單。

MDN: 2D collision detection

if (rect1.x < rect2.x + rect2.width && 
    rect1.x + rect1.width > rect2.x && 
    rect1.y < rect2.y + rect2.height && 
    rect1.height + rect1.y > rect2.y) 
{ 
    // collision detected! 
} 
+0

我正在使用'Rectangle'而不是'Rect',所以這不會對我有用 –

+1

肯定會''Rectangle x:Name =「rect1」Canvas.Left =「100」Canvas.Top =「100」Fill =「Red」Width =「100」Height =「100」>'只要取左= x,頂= y。這隻需要一點點數學就可以了。 –

+0

感謝這工作,我忘了使用'帆布'。我首先使用'Grid'來使用'Margin'作爲位置。 –

1

一個非常簡單的例子,如果你有這些矩形的引用,你可以easyly使用IntersectsWith - 方法尋找一個碰撞和Intersect - 方法得到的碰撞大小:

var rect1 = rectangle1.RenderedGeometry.Bounds; // get the rect struct 
var rect2 = rectangle2.RenderedGeometry.Bounds; // get the rect struct 

if (rect1.IntersectsWith(rect2)) 
{ 
    // get the area of the collision 
    var collisionRect = Rectangle.Intersect(rect1, rect2); 
} 

這樣您就不必手動計算位置和可能的碰撞。

+0

繼續收到錯誤「System.Windows.Rect」不包含「IntersectWith」的定義 –

+0

您是對的。 'System.Windows.Shapes.Rectangle'類不公開任何相交方法。但是你可以通過'Rect'結構得到相應的邊界。我更新了我的答案。 – khlr