// Check if this polygon intersects with another public new bool IntersectsWith(ConvexPolygon polygon) { // Suppose we have two polygons, A and B. Let e be an arbitrary edge of // polygon A or B, a be the unit vector perpendicular to e, and pA and pB // be the projections of polygons A and B onto a. If there exists an // edge e such that pA intersect pB is empty, then the polygons are not // overlapping. // Entry logging #if IS_LOGGING_METHODS Log.Write(String.Format("Entering method for {0}", this.Name)); #endif // Initialize result as true bool result = true; #region [1] Broad phase: Bounding box test // If the polygons' bounding boxes do not intersect, then surely the // polygons themselves do not either if (!this.MinBoundingBox.IntersectsWith(polygon.MinBoundingBox)) { result = false; goto exit; } #endregion #region [2] Narrow phase: SAT test // Initialize pastSlopes list List <float> pastSlopes = new List <float>(); // Count this polygon's vertices int n = this.Vertices.Count; // Count other polygon's vertices int m = polygon.Vertices.Count; // Get this polygon's edges List <LineSegment> edgesA = this.Edges; // Get other polygon's edges List <LineSegment> edgesB = polygon.Edges; // Loop through edges for (int i = 0; i < n + m; i++) { // Point to current edge LineSegment edge; if (i < n) { edge = edgesA[i]; } else { edge = edgesB[i - n]; } // Get edge's unit normal vector, i.e. the 'axis' Vector2 axis = (edge.Point2 - edge.Point1).Unit.Normal; // Get axis slope float slope = axis.Slope; // Initialize slopeAlreadyTested as false bool slopeAlreadyTested = false; // Check if former iteration already checked this slope for (int j = 0; j < pastSlopes.Count; j++) { if (slope == pastSlopes[j]) { slopeAlreadyTested = true; break; } } // If slopeAlreadyTested, then skip this iteration if (slopeAlreadyTested) { continue; } // Remember this slope for future iterations pastSlopes.Add(slope); // Project polygons onto axis Interval projectionA = this.ProjectOnto(axis); Interval projectionB = polygon.ProjectOnto(axis); // Check if their projections intersect if (!projectionA.IntersectsWith(projectionB)) { // If not, then the polygons do not intersect result = false; goto exit; } } #endregion // [*] Exit trap exit: // Exit logging #if IS_LOGGING_METHODS Log.Write(String.Format("Exiting method for {0}", this.Name)); #endif // Return result return(result); }