2013-04-21 28 views
2

c#中是否有预定义的方法可以进行碰撞检测?如何做c#碰撞检测?

我是新来的c#和我试图得到两个椭圆的碰撞检测是否有任何预定义的方式可以实现碰撞检测?

我已经有绘制椭圆的代码,那么启动碰撞检测的好方法是什么?

private void timer1_Tick(object sender, EventArgs e) 
    { 
     //Remove the previous ellipse from the paint canvas. 
     canvas1.Children.Remove(ellipse); 

     if (--loopCounter == 0) 
      timer.Stop(); 

     //Add the ellipse to the canvas 
     ellipse = CreateAnEllipse(20, 20); 
     canvas1.Children.Add(ellipse); 

     Canvas.SetLeft(ellipse, rand.Next(0, 500)); 
     Canvas.SetTop(ellipse, rand.Next(0, 310)); 
    } 

    // Customize your ellipse in this method 
    public Ellipse CreateAnEllipse(int height, int width) 
    { 
     SolidColorBrush fillBrush = new SolidColorBrush() { Color = Colors.Yellow}; 
     SolidColorBrush borderBrush = new SolidColorBrush() { Color = Colors.Black }; 

     return new Ellipse() 
     { 
      Height = height, 
      Width = width, 
      StrokeThickness = 1, 
      Stroke = borderBrush, 
      Fill = fillBrush 
     }; 
    } 

这是绘制椭圆然后被移除并出现在另一个位置的代码。

+0

你能发表该代码的例子吗? – 2013-04-21 15:57:13

+0

wpf不是一个游戏框架,它没有类似精灵般的功能,如碰撞检测。你可以做的最好的办法是获得两个椭圆的边界矩形,并使用'RectangleF.IntersectsWith'。否则,您将不得不计算两个椭圆的接近角度,即该角度的半径,然后查看两个半径的长度是否小于或等于两个椭圆的焦点之间的距离。 – 2013-04-21 16:05:42

回答

5

我已经测试了这一点,它的工作,对我来说

enter image description here

var x1 = Canvas.GetLeft(e1); 
var y1 = Canvas.GetTop(e1); 
Rect r1 = new Rect(x1, y1, e1.ActualWidth, e1.ActualHeight); 


var x2 = Canvas.GetLeft(e2); 
var y2 = Canvas.GetTop(e2); 
Rect r2 = new Rect(x2, y2, e2.ActualWidth, e2.ActualHeight); 

if (r1.IntersectsWith(r2)) 
    MessageBox.Show("Intersected!"); 
else 
    MessageBox.Show("Non-Intersected!"); 
+0

你帮我,我有一个主意!从你的回答 – 2014-03-26 18:13:25

1

至少我想你肯定应该给看看XNA framework,它有方法做碰撞检测的负荷。

看看这个其他link关于如何在c#中手动实现它可能会有所帮助。

+1

xna是矫枉过正,因为OP不开发游戏。 – David 2013-04-21 16:21:48

0

只要你的椭圆总是圆(即其WidthHeight属性设置为相同的值),他们总是有Canvas.LeftCanvas.Top属性设置,下面的辅助方法检查碰撞:

public static bool CheckCollision(Ellipse e1, Ellipse e2) 
{ 
    var r1 = e1.ActualWidth/2; 
    var x1 = Canvas.GetLeft(e1) + r1; 
    var y1 = Canvas.GetTop(e1) + r1; 
    var r2 = e2.ActualWidth/2; 
    var x2 = Canvas.GetLeft(e2) + r2; 
    var y2 = Canvas.GetTop(e2) + r2; 
    var d = new Vector(x2 - x1, y2 - y1); 
    return d.Length <= r1 + r2; 
} 
2

会像下面的工作?

var ellipse1Geom = ellipse1.RenderedGeometry; 
var ellipse2Geom = ellipse2.RenderedGeometry; 
var detail = ellipse1Geom.FillContainsWithDetail(ellipse2Geom); 
if(detail != IntersectionDetail.Empty) 
{ 
    // We have an intersection or one contained inside the other 
} 

Geometry.FillContainsWithDetail(Geometry)方法被定义为

返回描述当前几何结构和给定的几何之间的交点的值。