private static Point2D.Double intersectEntityWithSegment(
        Entity entity,
        Line2D.Double segment)
    {
        // Best intersection distance so far.
        double bestDistance = 1000.0;

        // Point where the best intersection is.
        Point2D.Double bestIntersection = null;

        // Try intersecting the line segment with each segment of the
        // entity edge.
        for (int i=0; i<4; i++) {
            // Line segment on border of entity.
            Line2D.Double entitySeg = getEntitySegment(entity, i);

            // Intersect with the given segments, yielding parameters
            // that indicate how far along each segment to go to reach
            // the intersection point.
            double t = GeomUtil.intersectLine2Ds(segment, entitySeg);
            double t2 = GeomUtil.intersectLine2Ds(entitySeg, segment);
            if (Util.isSpecialDouble(t) || Util.isSpecialDouble(t2)) {
                continue;
            }

            // Compute "distance" to perfect intersection: the amount
            // that 't' or 't2' is beyond the range [0,1], using the
            // larger distance if both are outside that range.  It is
            // zero if both are in [0,1], meaning the segments truly
            // intersect.
            double distance = 0.0;
            if (t < 0.0) {
                distance = Math.max(distance, 0.0 - t);
            }
            if (t > 1.0) {
                distance = Math.max(distance, t - 1.0);
            }
            if (t2 < 0.0) {
                distance = Math.max(distance, 0.0 - t2);
            }
            if (t2 > 1.0) {
                distance = Math.max(distance, t2 - 1.0);
            }

            // True intersection?
            if (distance == 0.0) {
                return GeomUtil.pointOnLine2D(entitySeg, t);
            }

            // Best so far?
            if (distance < bestDistance) {
                bestDistance = distance;
                bestIntersection = GeomUtil.pointOnLine2D(entitySeg, t);
            }
        }

        // We might not have a true intersection, but we'll use it anyway.
        // Non-intersections seem to happen fairly frequently when the
        // intersection point is near a corner of the entity rectangle.
        return bestIntersection;
    }