Recently I’ve needed some shape based hit detection in As 3.0 so as a starting point I decided to convert Grant’s CollisionDetection class. I’ve split the code out into 3 methods and optimized it a bit by creating a BitmapData as small as possible .
Here’s a description and example of each of the methods.
ComplexHitTestObject
HitTest.complexHitTestObject( target1:DisplayObject, target2:DisplayObject, accuracy:Number );
ComplexHitTestObject example
Returns a Boolean depending on whether the 2 DisplayObjects passed as parameters are overlapping each other. The 3rd parameter specifies how accurate the test it. The higher the number, the greater the size the BitmapData is drawn internally, and therefore the scale at which the 2 DisplayObjects are drawn onto the BitmapData. The default for the accuracy parameter is 1. If you try and pass a value of 0 or less the method will thorw an error.
IntersectionRectangle
HitTest.intersectionRectangle( target1:DisplayObject, target2:DisplayObject );
IntersectionRectangle example
Returns a Rectangle matching the co-ordinates where the boundaries of the 2 DisplayObjects passed as parameters overlap. This method does a simple test much like hitTestObject().
ComplexIntersectionRectangle
HitTest.complexIntersectionRectangle( target1:DisplayObject, target2:DisplayObject, accuracy:Number );
ComplexIntersectionRectangle example
Returns a Rectangle matching the co-ordinates where the 2 DisplayObjects passed as parameters overlap. The 3rd parameter specifies how accurate the test it. The higher the number, the greater the size the BitmapData is drawn internally, and therefore the scale at which the 2 DisplayObjects are drawn onto the BitmapData. The default for the accuracy parameter is 1. If you try and pass a value of 0 or less the method will thorw an error.
You can view the source in any of the examples above by right clicking and selecting ‘View source’. Each include the HitTest class, also included below.
(more…)