c# - 如何进行 C# 碰撞检测?

标签 c# wpf ellipse

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

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

最佳答案

我已经测试过了,它有效,至少对我来说是这样

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

关于c# - 如何进行 C# 碰撞检测?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16132903/

相关文章:

c# - Visual Studio 如何知道源文件是否与原始版本匹配?

wpf - 在 VisualState Storyboard 中使用绑定(bind)

matlab - 如何减去单位正方形外的椭圆面积?

c# - HttpContext.Current.Request.Form 复选框

c# - 从 .NET 桌面应用程序使用谷歌地图

c# - 如何在 C# 中将用户从登录表单重定向到另一个表单

c# - 具有多个 UI : WPF and Mobile website (asp.net 的新应用程序)

c# - WPF: slider 不会提升 MouseLeftButtonDown 或 MouseLeftButtonUp

r - 使用 R 将数据点拟合到中心在原点的椭圆

python - 如何找到椭圆的方程式