Bounding Box of a Rotated Rectangle

admin  

In action script is possible to find out the bounding box of a rotated sprite(rectangles can be used as well) using DisplayObject.getBounds method. In this post I’ll show a pure mathematic/geometrical approach. It has the advantages that can be ported in other languages, can be used independently of AS3 display list and assumingly is much faster that the as3 function.

The method to return the bounding box of the rotated rectangle works very easy. We calculate for each of the 5 corners of the rectangle the new position when is rotated, using the following formula(see Transformation Matrix on wikipedia):

After each corner is rotated we choose the minimum and maximum x and y to represent the corners of the bounding box of the rotated rectangle:

static public function boundingRectForRect(centerX:Number, centerY:Number, x1:Number, y1:Number, x2:Number, y2:Number, angleRadians:Number):Rectangle
        {
            var x1prim:Number = (x1 - centerX) * Math.cos(angleRadians) - (y1 - centerX) * Math.sin(angleRadians);
            var y1prim:Number = (x1 - centerX) * Math.sin(angleRadians) + (y1 - centerX) * Math.cos(angleRadians);
            
            var x12prim:Number = (x1 - centerX) * Math.cos(angleRadians) - (y2 - centerX) * Math.sin(angleRadians);
            var y12prim:Number = (x1 - centerX) * Math.sin(angleRadians) + (y2 - centerX) * Math.cos(angleRadians);
            
            var x2prim:Number = (x2 - centerX) * Math.cos(angleRadians) - (y2 - centerX) * Math.sin(angleRadians);
            var y2prim:Number = (x2 - centerX) * Math.sin(angleRadians) + (y2 - centerX) * Math.cos(angleRadians);

            var x21prim:Number = (x2 - centerX) * Math.cos(angleRadians) - (y1 - centerX) * Math.sin(angleRadians);
            var y21prim:Number = (x2 - centerX) * Math.sin(angleRadians) + (y1 - centerX) * Math.cos(angleRadians);			
            
            var rx1:Number = centerX + Math.min(x1prim, x2prim, x12prim, x21prim);
            var ry1:Number = centerY + Math.min(y1prim, y2prim, y12prim, y21prim);
            
            var rx2:Number = centerX + Math.max(x1prim, x2prim, x12prim, x21prim);
            var ry2:Number = centerY + Math.max(y1prim, y2prim, y12prim, y21prim);
            
            return new Rectangle(rx1, ry1, rx2 - rx1, ry2 - ry1);			
        }

In the following section you can see the algorithm in action.

The same method can be extended to detect the bounding box for polygons or triangles. Bounding boxes are easy and efficient to calculate and they can be used in collision detection algorithms. Usually collision detection done only through bounding boxes is not very robust, but it can be used to see if better but less efficient algorithms are required to run when 2 bounding boxes overlaps.