Reputation: 1349
I am making a game in C# and XNA and I am using three Points to represent the hitbox of an enemy object. A Rectangle variable is used to represent the player's hitbox. I am using three Points for the enemy rather than a rectangle as the enemy is shaped like a triangle.
//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);
I need a way to determine if the Rectangle overlaps the area between all of the Points, as shown in the following pictures. Would anybody be able to show me a method or some kind of code that could help me accomplish this?
Upvotes: 2
Views: 549
Reputation: 5519
Here is an alternative implementation:
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;
}
}
Upvotes: 2