如何进行C#碰撞检测?

4

在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
        }; 
    }

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


你能发一下那段代码的例子吗? - m.edmondson
WPF不是游戏框架,它没有像碰撞检测这样的精灵功能。你能做的最好的事情就是获取两个椭圆的边界矩形并使用RectangleF.IntersectsWith。否则,你将不得不计算两个椭圆相遇的角度、该角度处的半径,然后看看添加两个半径的长度是否小于或等于椭圆的两个焦点之间的距离。 - Peter Ritchie
4个回答

6

我已经测试过这个,它能够正常工作,至少对我有效。

在此输入图片描述

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

你帮了我,我有了一个想法!来自你的回答。 - Tech Nerd

4
以下的东西是否能行?
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)方法被定义为:

返回一个值,描述当前几何图形和指定几何图形之间的交集。


1
假设您的椭圆始终为圆形(即它们的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;
}

1
我认为你应该一定要看看XNA框架,它有很多方法可以进行碰撞检测。
查看这个链接上的内容,了解如何在C#中手动实现它可能会有帮助。

1
XNA 过于复杂,因为 OP 并非在开发游戏。 - David

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接