2015-01-17 26 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