Example #1
0
        /// <summary>
        /// If an intersection with the frame occurs do the minimal translation to undo the overlap
        /// </summary>
        /// <param name="rectangleB">The AABR to check for intersect</param>
        public static void UndoOverlap(this Box2D rectangleA, Box2D rectangleB)
        {
            if (!rectangleA.Intersects(rectangleB))
            {
                return;
            }

            Vector2[] directions = new Vector2[]
            {
                new Vector2(rectangleB.MaxX - rectangleA.X, 0),                 // push distance A in positive X-direction
                new Vector2(rectangleB.X - rectangleA.MaxX, 0),                 // push distance A in negative X-direction
                new Vector2(0, rectangleB.MaxY - rectangleA.Y),                 // push distance A in positive Y-direction
                new Vector2(0, rectangleB.Y - rectangleA.MaxY)                  // push distance A in negative Y-direction
            };
            float[] pushDistSqrd = new float[4];
            for (int i = 0; i < 4; ++i)
            {
                pushDistSqrd[i] = directions[i].LengthSquared();
            }
            //find minimal positive overlap amount
            int minId = 0;

            for (int i = 1; i < 4; ++i)
            {
                minId = pushDistSqrd[i] < pushDistSqrd[minId] ? i : minId;
            }

            rectangleA.X += directions[minId].X;
            rectangleA.Y += directions[minId].Y;
        }
Example #2
0
        /// <summary>
        /// Calculates the AABR in the overlap
        /// Returns null if no intersection
        /// </summary>
        /// <param name="rectangleB"></param>
        /// <returns>AABR in the overlap</returns>
        public static Box2D Overlap(this Box2D rectangleA, Box2D rectangleB)
        {
            Box2D overlap = null;

            if (rectangleA.Intersects(rectangleB))
            {
                overlap = new Box2D(0.0f, 0.0f, 0.0f, 0.0f);

                overlap.X = (rectangleA.X < rectangleB.X) ? rectangleB.X : rectangleA.X;
                overlap.Y = (rectangleA.Y < rectangleB.Y) ? rectangleB.Y : rectangleA.Y;

                overlap.SizeX = (rectangleA.MaxX < rectangleB.MaxX) ? rectangleA.MaxX - overlap.X : rectangleB.MaxX - overlap.X;
                overlap.SizeY = (rectangleA.MaxY < rectangleB.MaxY) ? rectangleA.MaxY - overlap.Y : rectangleB.MaxY - overlap.Y;
            }

            return(overlap);
        }