public static bool PointInsidePoly(Vector2Int point, Vector2Int[] poly) { FlatBounds bounds = new FlatBounds(); foreach (Vector2Int polyPoint in poly) { bounds.Encapsulate(polyPoint.vector2); } if (!bounds.Contains(point.vector2)) { return(false); } Vector2Int pointRight = point + new Vector2Int(bounds.width, 0); int numberOfPolyPoints = poly.Length; int numberOfCrossOvers = 0; for (int i = 0; i < numberOfPolyPoints; i++) { Vector2Int p0 = poly[i]; Vector2Int p1 = poly[(i + 1) % numberOfPolyPoints]; if (FastLineIntersection(point, pointRight, p0, p1)) { numberOfCrossOvers++; } } // if(numberOfCrossOvers % 2 != 0) bounds.DrawDebug(Color.green); return(numberOfCrossOvers % 2 != 0); }
public static bool SweepIntersects(Vector2 a1, Vector2 a2, Vector2 b1, Vector2 b2, Vector2 l1, Vector2 l2, out Vector2 intersection, out float percent, float accuracy = 1) { intersection = Vector2.zero; percent = 0; Vector2 lineDelta = l2 - l1; Vector2 point = l2; b1 += -lineDelta; b2 += -lineDelta; Vector2[] poly = { a1, a2, b2, b1 }; FlatBounds bounds = new FlatBounds(poly); if (!bounds.Contains(l1)) { return(false); } // bounds.DrawDebug(Color.yellow); Vector2 pointRight = point + new Vector2(Mathf.Max(bounds.width, bounds.height), 0); // Vector2 pointRight = point - lineDelta * bounds.width * bounds.height; // Debug.DrawLine(ToV3(point), ToV3(pointRight), Color.cyan); int numberOfPolyPoints = poly.Length; int numberOfCrossOvers = 0; for (int i = 0; i < numberOfPolyPoints; i++) { Vector2 p0 = poly[i]; Vector2 p1 = poly[(i + 1) % numberOfPolyPoints]; // Debug.DrawLine(ToV3(p0), ToV3(p1), Color.blue); if (FastLineIntersection(point, pointRight, p0, p1)) { numberOfCrossOvers++; } } if (numberOfCrossOvers % 2 == 0) { return(false);//point not within shape } bounds.DrawDebug(Color.green); Vector2 delta1 = b1 - a1; Vector2 delta2 = b2 - a2; float maxDelta = Mathf.Max(delta1.magnitude, delta2.magnitude); int iterations = Mathf.CeilToInt(Mathf.Sqrt(maxDelta / accuracy)); for (int i = 0; i < iterations; i++) { Vector2 c1 = Vector2.Lerp(a1, b1, 0.5f); Vector2 c2 = Vector2.Lerp(a2, b2, 0.5f); if (!Ccw(c1, c2, point)) { a1 = c1; a2 = c2; percent = Mathf.Lerp(percent, 1, 0.5f); } else { b1 = c1; b2 = c2; percent = Mathf.Lerp(0, percent, 0.5f); } } // Vector2 x1 = Vector2.Lerp(a1, b1, 0.5f); // Vector2 x2 = Vector2.Lerp(a2, b2, 0.5f); // float dist1 = Vector2.Distance(x1, point); // float dist2 = Vector2.Distance(x2, point); // float xpercent = dist1 / (dist1 + dist2); // intersection = Vector2.Lerp(x1, x2, xpercent); intersection = Vector2.Lerp(l1, l2, percent);//translate the point to the real movement point Debug.DrawLine(ToV3(intersection), ToV3(intersection) + Vector3.up * 5, Color.red); return(true); }