Exemplo n.º 1
0
        /// <summary>
        /// iterates all the edges of the polygon and gets the closest point on any edge to point. Returns via out the squared distance
        /// to the closest point and the normal of the edge it is on. point should be in the space of the Polygon (point - poly.position)
        /// </summary>
        /// <returns>The closest point on polygon to point.</returns>
        /// <param name="point">Point.</param>
        /// <param name="distanceSquared">Distance squared.</param>
        /// <param name="edgeNormal">Edge normal.</param>
        public static Vector2 GetClosestPointOnPolygonToPoint(Vector2[] points, Vector2 point, out float distanceSquared, out Vector2 edgeNormal)
        {
            distanceSquared = float.MaxValue;
            edgeNormal      = Vector2.Zero;
            var closestPoint = Vector2.Zero;

            float tempDistanceSquared;

            for (var i = 0; i < points.Length; i++)
            {
                var j = i + 1;
                if (j == points.Length)
                {
                    j = 0;
                }

                var closest = ShapeCollisions.ClosestPointOnLine(points[i], points[j], point);
                Vector2.DistanceSquared(ref point, ref closest, out tempDistanceSquared);

                if (tempDistanceSquared < distanceSquared)
                {
                    distanceSquared = tempDistanceSquared;
                    closestPoint    = closest;

                    // get the normal of the line
                    var line = points[j] - points[i];
                    edgeNormal.X = -line.Y;
                    edgeNormal.Y = line.X;
                }
            }

            Vector2Ext.Normalize(ref edgeNormal);

            return(closestPoint);
        }