Recently I had a need for shape-based collision detection and decided to write up a class to handle it. As the class developed, I discovered other things that would be nice to have but weren't available, so I worked it out and added the functionality to my class.
Long story short, it developed into a small package of code I call the Collision Detection Kit. It's been so useful for me that I've decided to put it under an MIT license and share it with all of you.
It uses bitmapdata to find overlapping pixels of display objects. Not a new idea, I realize, but I wrote mine out from scratch anyways to handle things the way I needed them handled. This allowed me to figure out a few other nifty features that I include in the kit. Here are the big ones that me and my beta testers/coworkers have been loving:
- Set an alpha threshold so that any pixels on a display object below that alpha won't be checked for collisions.
- Exclude colors and color ranges from collision detection.
- The kit can approximate the angle of a collision, allowing you to keep your physics convincing when colliding with odd/organic shapes. It took awhile to figure out a good way of doing this. It's my favorite part of the kit.
- Gives you the pixels that overlap in a collision in stage coordinates, making it easier for you to adjust positions or apply off-center rotation convincingly.
- The kit takes nesting into account, so it doesn't matter where your display objects are on the display list.
- Takes transforms into account for individual instances, so things like scaling, rotating, and performing color transforms on your objects are no problem. This includes transformation made to any parent containers!
- Can be used with display objects on or off the display list. Works great alongside blitting engines.
- Works with all display objects: MovieClips, Sprites, TextFields (very cool), FLVs, etc.
I've created pre-compiled examples to show off these features and give you a better idea of what this package is capable of doing. I also have all classes documented, available online and for download (includes some rudimentary source code examples).
Feedback is welcomed! I don't have a discussion list for this yet, but plan on adding that or a forum later this evening (via Google Code). In the meanwhile, post any questions you might have here. I hope this can help some people out, as it's helped me a ton!
A new version of the CDK (v1.5) is now available! Links have been updated. I'm thrilled that the CDK has been so useful to so many devs, and I'm glad to finally be pushing out this update based on user feedback. Enjoy!