Example #1
0
        public static bool TestLineSegmentWithConvexPolygon(Vector2 startPoint, Vector2 endPoint, Polygon polygon, IEnumerable <Vector2> axes, out Contact?contact)
        {
            Vector2[] intersections = polygon.Intersects(new Line(startPoint, endPoint));

            // no intersections, no contact
            if (intersections.Length == 0)
            {
                contact = null;
                return(false);
            }

            Contact leastPenetrationContact = new Contact {
                Position         = intersections[0],
                PenetrationDepth = float.PositiveInfinity
            };

            // calculate line-segment first contact point position
            float closestIntersectionDist = Math.DistanceSquared(startPoint, intersections[0]);

            for (int i = 1; i < intersections.Length; i++)
            {
                float d = Math.DistanceSquared(startPoint, intersections[i]);
                if (d < closestIntersectionDist)
                {
                    leastPenetrationContact.Position = intersections[i];
                    closestIntersectionDist          = d;
                }
            }

            foreach (Vector2 axis in axes)
            {
                Range projectionA        = axis.Projection(startPoint, endPoint),
                             projectionB = polygon.Projection(axis);

                if (!projectionA.Overlaps(projectionB, out float penetrationDepth))
                {
                    contact = null;
                    return(false);
                }

                if (penetrationDepth < leastPenetrationContact.PenetrationDepth)
                {
                    leastPenetrationContact.PenetrationDepth = penetrationDepth;
                    leastPenetrationContact.Normal           = projectionA.Min > projectionB.Min ? -axis : axis;
                }
            }

            contact = leastPenetrationContact;
            return(true);
        }
Example #2
0
        public bool Intersects(Polygon polygon)
        {
            foreach (Vector2 vertex in polygon)
            {
                if (ContainsInclusive(vertex))
                {
                    return(true);
                }
            }

            foreach (Line edge in Edges())
            {
                if (polygon.Intersects(edge).Length > 0 || polygon.IsInside(edge.PointA))
                {
                    return(true);
                }
            }

            return(false);
        }