本文介绍了如何做到C#碰撞检测?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有在C#中任何预定义的方法,允许碰撞检测?

Are there any predefined methods in c# which allow for collision detection?

我是新的C#和想获得两个椭圆的碰撞检测是否有任何预定义如何碰撞检测可以实现?

I am new to c# and am trying to get collision detection of two ellipses are there any predefined ways collision detection can be implemented?

我已经有代码,绘制椭圆,这将是一个很好的方式开始碰撞检测?

I already have code which draws the ellipses, what would be a good way to start the collision detection?

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

这是画然后把它删除,并显示在另外一个椭圆的代码位置。

this is the code to draw an ellipse which then gets removed and appears in another position.

推荐答案

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

I have tested this, it worked, at least for me

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#碰撞检测?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 06:22