如何检查矩形是否与三个点之间的区域重叠? (C#和XNA)

时间:2015-08-20 23:44:16

标签: c# xna point intersect

我正在用C#和XNA制作一个游戏,我使用三个点代表一个敌方物体的命中箱。 Rectangle变量用于表示玩家的hitbox。我使用三个点作为敌人而不是一个矩形,因为敌人的形状像三角形。

//Example coordinates
Point pointOne = new Point(0, 50);
Point pointTwo = new Point(50, 50);
Point pointThree = new Point(25, 0);
Rectangle rect = new Rectangle(0, 0, 10, 10);

我需要一种方法来确定矩形是否与所有点之间的区域重叠,如下图所示。是否有人能够向我展示一种方法或某种代码可以帮助我实现这一目标?

enter image description here enter image description here enter image description here

1 个答案:

答案 0 :(得分:2)

以下是另一种实施方式:

class Triangle
{
    Vector2 topPoint, rightPoint, leftPoint;


    public Triangle(Vector2 p1, Vector2 p2, Vector2 p3)
    {
        topPoint = p1;
        rightPoint = p2;
        leftPoint = p3;
    }



    public bool IsRectIntersecting(List<Vector2> corners)//corners are the corners of the polygon being tested
    {


        if (AreAnyOfTheCornesInsideTriangleLineSegment(topPoint, rightPoint, corners) && 
            AreAnyOfTheCornesInsideTriangleLineSegment(rightPoint, leftPoint, corners) && 
            AreAnyOfTheCornesInsideTriangleLineSegment(leftPoint, topPoint, corners))
        {
            return true;
        }

        return false;
    }

    private bool AreAnyOfTheCornesInsideTriangleLineSegment(Vector2 pointA, Vector2 pointB, List<Vector2> corners)
    {
        Vector2 lineSegment = pointA - pointB;
        Vector3 lineSegment3D = new Vector3(lineSegment, 0);
        Vector3 normal3D = Vector3.Cross(lineSegment3D, Vector3.UnitZ);
        Vector2 normal = new Vector2(normal3D.X, normal3D.Y);

        foreach (Vector2 corner in corners)
        {
            if (Vector2.Dot(normal, corner - pointB) < 0)
            {
                return true;
            }
        }

        return false;
    }
}