package com.philperon.display { import flash.display.BitmapData; import flash.display.BlendMode; import flash.display.DisplayObject; import flash.geom.ColorTransform; import flash.geom.Matrix; import flash.geom.Rectangle; public class Collision { public static function collisionTest(dispObj1:DisplayObject, dispObj2:DisplayObject, alphaTolerance:uint = 0):Rectangle { var rect1:Rectangle = dispObj1.getBounds(dispObj1.stage); var rect2:Rectangle = dispObj2.getBounds(dispObj2.stage); var objectIntersection:Rectangle = rect1.intersection(rect2); // don't bother with width or height values < 1. if((objectIntersection.width < 1) || (objectIntersection.height < 1)) return null; var bitmapData:BitmapData = new BitmapData(objectIntersection.width, objectIntersection.height, false); var mat:Matrix = dispObj1.transform.concatenatedMatrix; mat.tx -= objectIntersection.left; mat.ty -= objectIntersection.top; bitmapData.draw(dispObj1, mat, new ColorTransform(1, 1, 1, 1, 255, -255, -255, alphaTolerance)); mat = dispObj2.transform.concatenatedMatrix; mat.tx -= objectIntersection.left; mat.ty -= objectIntersection.top; bitmapData.draw(dispObj2, mat, new ColorTransform(1, 1, 1, 1, 255, 255, 255, alphaTolerance), BlendMode.DIFFERENCE); var pixelIntersection:Rectangle = bitmapData.getColorBoundsRect(0xFFFFFFFF, 0xFF00FFFF); if(pixelIntersection.width == 0) return null; pixelIntersection.x += objectIntersection.left; pixelIntersection.y += objectIntersection.top; return pixelIntersection; } } }