/// <summary> /// Do a narrow phase collision check between two shapes by using SAT (Separating Axis Theorem). /// If a collision has occurred, get the MTV (Minimum Translation Vector) of the two intersecting shapes. /// </summary> /// <param name="s1">The first shape to check.</param> /// <param name="s2">The second shape to check.</param> /// <returns>The MTV of the intersection.</returns> public CollisionData NarrowPhase(Shape s1, Shape s2) { // The minimum amount of overlap. Start real high. float overlap = float.MaxValue; //The collision data. CollisionData data = new CollisionData(s1, s2); // The smallest axis found. Vector2 smallest = Vector2.Zero; try { // Get the axes of both bodies. Vector2[][] axes = new Vector2[][] { s1.GetAxes(), s2.GetAxes() }; // Iterate over the axes of both bodies. foreach (Vector2[] v in axes) { // Iterate over both bodies' axes. foreach (Vector2 a in v) { // Project both bodies onto the axis. Vector2 p1 = s1.Project(a); Vector2 p2 = s2.Project(a); // Get the overlap. float o = Calculator.GetOverlap(p1, p2); // Do the projections overlap? if (o == -1) { // We can guarantee that the shapes do not overlap. return data; } else { // Check for minimum. if (o < overlap) { // Store the minimum overlap and the axis it was projected upon. Make sure that the separation vector is pointing the right way. overlap = o; smallest = a; } } } } } catch (Exception e) { Console.WriteLine(this + ": Narrow Phase Error. (" + e + ")"); } // We now know that every axis had an overlap on it, which means we can guarantee an intersection between the bodies. data.HasCollision = true; data.Axis = smallest; data.Overlap = overlap; //Return the collision data. return data; }