Skip to main content
 首页 » 编程设计

c#之如何在 Monogame 中创建一个圆变量并检测与其他圆/矩形的碰撞

2024年02月06日13lori

我正在尝试制作一个区域效果特征。到目前为止,我一直通过检查一个矩形是否与另一个矩形相交来管理碰撞。

这很简单,因为我只创建了 2 个 Rectangle 变量并检查它们是否相交。但是,我似乎找不到创建 Circle 变量的简单方法。

如何创建一个半径为 r 的圆,然后检查是否有任何矩形/圆与其相交?

请您参考如下方法:

碰撞检测和响应可能是一个复杂的话题。但是,如果您只需要几种基本的碰撞类型,计算起来会非常简单。

请注意,一旦开始涉及比圆形和矩形更复杂的旋转和形状,事情就会变得有点棘手。此外,这取决于您在检测到碰撞后要执行的操作。移动的形状比静止的形状需要更多的工作。

如果您确实需要这些更复杂的东西,我建议您看一下 Farseer Physics 或 Box2D.XNA 等物理引擎。

也就是说,让我们分解计算。

正如您所说,2 个矩形之间的碰撞检测非常简单:

var rectangle1 = new Rectangle(100, 200, 300, 400); 
var rectangle2 = new Rectangle(150, 250, 350, 450); 
 
if(rectangle1.Intersects(rectangle2)) 
{ 
    // do your thing 
} 

现在,假设我们创建了一个以类似方式运行的 Circle 类。

public struct Circle 
{ 
    public Circle(int x, int y, int radius) 
        : this() 
    { 
        X = x; 
        Y = y; 
        Radius = radius; 
    } 
 
    public int Radius { get; private set; } 
    public int X { get; private set; } 
    public int Y { get; private set; } 
 
    public bool Intersects(Rectangle rectangle) 
    { 
        // the first thing we want to know is if any of the corners intersect 
        var corners = new[] 
        { 
            new Point(rectangle.Top, rectangle.Left), 
            new Point(rectangle.Top, rectangle.Right), 
            new Point(rectangle.Bottom, rectangle.Right), 
            new Point(rectangle.Bottom, rectangle.Left) 
        }; 
 
        foreach (var corner in corners) 
        { 
            if (ContainsPoint(corner)) 
                return true; 
        } 
 
        // next we want to know if the left, top, right or bottom edges overlap 
        if (X - Radius > rectangle.Right || X + Radius < rectangle.Left) 
            return false; 
 
        if (Y - Radius > rectangle.Bottom || Y + Radius < rectangle.Top) 
            return false; 
 
        return true; 
    } 
 
    public bool Intersects(Circle circle) 
    { 
        // put simply, if the distance between the circle centre's is less than 
        // their combined radius 
        var centre0 = new Vector2(circle.X, circle.Y); 
        var centre1 = new Vector2(X, Y); 
        return Vector2.Distance(centre0, centre1) < Radius + circle.Radius; 
    } 
 
    public bool ContainsPoint(Point point) 
    { 
        var vector2 = new Vector2(point.X - X, point.Y - Y); 
        return vector2.Length() <= Radius; 
    } 
} 

现在,如果我的计算正确(我在脑海中记下了这个),您应该能够像使用 XNA/MonoGame Rectangle 类一样使用新的 Circle 类。

但是,您可能在这个过程中也意识到现在实际上有几种不同的碰撞组合。圆-圆、矩形-矩形、矩形-圆,有时倒转圆-矩形很方便。如果将所有这些方法都放在实际的形状类上,这可能会变得非常难以管理(并且感觉不对)。我见过的大多数物理引擎通常都有一些碰撞辅助类,它们将所有这些方法都拉到一个静态类中。

祝你好运 :) 如果我犯了任何错误,请告诉我。