/// <summary> /// Finds the closets point on the polygon to the specified point. /// </summary> /// <param name="point">The point to find the closest point to.</param> /// <param name="vertices">The vertices describing the polygon.</param> /// <param name="numVertices">The number of actual vertices in the vertices array.</param> /// <returns>The point on the polygon that is closest to the specified point.</returns> public static Vector2 FindClosestPointOnPolygon(Vector2 point, Vector2[] vertices, int numVertices) { // Find the closest point Vector2 closestPoint = ShapeUtility.CalculateClosestPointOnEdge(point, vertices[0], vertices[1]); float closestDistance = (closestPoint - point).LengthSquared(); for (int i = 1; i < numVertices; i++) { Vector2 closestPointOfEdge = (i == numVertices - 1 ? ShapeUtility.CalculateClosestPointOnEdge(point, vertices[i], vertices[0]) : ShapeUtility.CalculateClosestPointOnEdge(point, vertices[i], vertices[i + 1])); float currentDistance = (closestPointOfEdge - point).LengthSquared(); if (currentDistance < closestDistance) { closestPoint = closestPointOfEdge; closestDistance = currentDistance; } } return(closestPoint); }
/// <summary> /// Checks for intersection between a polygon and a circle. /// </summary> /// <param name="polygon">The circle.</param> /// <param name="circle">The polygon.</param> /// <returns>True if the two shapes intersect. False othwerise.</returns> public static bool Intersects(IPolygon2D polygon, ICircle2D circle) { // See if the closest point of each edge to the circle's center is inside the center Vector2 circleCenter = circle.Center; for (int i = 0; i < polygon.NumSides; i++) { Vector2 closestPointOfEdge = (i == polygon.NumSides - 1 ? ShapeUtility.CalculateClosestPointOnEdge(circleCenter, polygon.Vertices[i], polygon.Vertices[0]) : ShapeUtility.CalculateClosestPointOnEdge(circleCenter, polygon.Vertices[i], polygon.Vertices[i + 1])); if (circle.Contains(closestPointOfEdge)) { return(true); } } // See if this polygon contains the other circle if (polygon.Contains(circle.Center)) { return(true); } return(false); }