怎么做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 }; } 

这是绘制椭圆的代码,然后将其移除并显示在另一个位置。

我测试了这个,它起作用了,至少对我而言

在此处输入图像描述

 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!"); 

会有类似下面的工作吗?

 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)方法定义为

返回描述当前几何与指定几何之间的交集的值。

我认为你一定要看看XNA框架 ,它有很多方法来做碰撞检测。

查看关于如何在c#中手动实现它的其他链接 ,这可能会有所帮助。

如果您的省略号始终是圆圈(即它们的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; }