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 :(得分:5)
我测试了这个,它起作用了,至少对我而言
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!");
答案 1 :(得分: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)
方法定义为
返回一个值,该值描述当前几何体与指定几何体之间的交集。
答案 2 :(得分:1)
我认为你绝对应该看看XNA framework,它有很多方法可以进行碰撞检测。
请查看其他link,了解如何在c#中手动实现它可能会有所帮助。
答案 3 :(得分:1)
如果您的省略号始终为圆圈(即他们的Width
和Height
属性设置为相同的值),并且它们始终设置Canvas.Left
和Canvas.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;
}