/// <summary>
/// Returns whether this instance collides with the argument Polygon.
/// </summary>
/// <param name="polygon">The Polygon to test collision against.</param>
/// <returns>Whether a collision has occurred.</returns>
#endregion
public bool CollideAgainst(Polygon polygon)
{
UpdateDependencies(TimeManager.CurrentTime);
polygon.UpdateDependencies(TimeManager.CurrentTime);
Point transformedPoint1 = new Point(RelativePoint1.X, RelativePoint1.Y);
Point transformedPoint2 = new Point(RelativePoint2.X, RelativePoint2.Y);
FlatRedBall.Math.MathFunctions.TransformPoint(ref transformedPoint1, ref mRotationMatrix);
FlatRedBall.Math.MathFunctions.TransformPoint(ref transformedPoint2, ref mRotationMatrix);
Point tp1 = new Point(transformedPoint1.X, transformedPoint1.Y);
Point tp2 = new Point(transformedPoint2.X, transformedPoint2.Y);
// Get world-positioned segment
Segment a = new Segment(
new Point(Position.X + transformedPoint1.X,
Position.Y + transformedPoint1.Y),
new Point(Position.X + transformedPoint2.X,
Position.Y + transformedPoint2.Y));
// Check if one of the segment's endpoints is inside the Polygon
if (polygon.IsPointInside(ref tp1, ref Position, ref mIdentityMatrix))
{
polygon.mLastCollisionPoint = tp1;
mLastCollisionPoint = tp1;
return(true);
}
if (polygon.IsPointInside(ref tp2, ref Position, ref mIdentityMatrix))
{
polygon.mLastCollisionPoint = tp2;
mLastCollisionPoint = tp2;
return(true);
}
Point intersectionPoint;
// Check if one of the polygon's edges intersects the line segment
for (int i = 0; i < polygon.Points.Count - 1; i++)
{
int indexAfter = i + 1;
var point1 = new Point(polygon.Vertices[i].Position.X,
polygon.Vertices[i].Position.Y);
var point2 = new Point(polygon.Vertices[indexAfter].Position.X,
polygon.Vertices[indexAfter].Position.Y);
if (a.Intersects(new Segment(point1, point2), out intersectionPoint))
{
mLastCollisionPoint = intersectionPoint;
polygon.mLastCollisionPoint = intersectionPoint;
return(true);
}
}
// No collision
return(false);
}