Most of the Flash 8 demos released so far using BitmapData have been purely visual, so I thought I should release one of my experiments that focuses on function.
One of the things that Flashers have wanted for years is shape based hit detection – that is, the ability to detect if one shape intersects with another shape. The best we’ve been able to do so far is test a single point against a clip’s shape, which obviously isn’t that great for games with complex interactions.
Flash 8 changes all of that. Unfortunately, it doesn’t give you an easy method to do it (mc.hitTestShape(mc2) would be nice), but it does give you all the tools you need to make it work. In the simple demo below (requires Flash Player 8r50, earlier versions will show whacky graphic artifacts), you can see shape based hit detection at work.
I know it’s ugly, but this is a functional demo, not an art piece [grin]. Welcome to the era of cheap, ugly bevels and dropshadows on everything – it’s like PhotoShop 5 (or was it 4?) all over again.
It uses a CollisionDetection class that I’ve built, and will release once Flash 8 is release (we have lots of goodies queued up). This is how the method works, in brief:
1) finds the boundary intersection of both clips
2) creates a bitmap the same size as the intersection
3) draws the first clip into the bitmap in red
4) draws the second clip into the bitmap in white, using a difference blend
5) returns the boundaries of cyan in the bitmap (white difference blended on red makes cyan), or null if there is no cyan
You can see the resultant bitmap in the top left corner of the demo.
Because all of the heavy lifting is done in the player, it runs quite quickly (about 2-3ms per comparison). It also supports color transformations that allow me to set an alpha threshold for comparisons (in this example, I using this feature to avoid collisions with the drop shadow). Before Tinic berates me, there is also a method built into BitmapData that will compare two transparent bitmaps, which would be faster if you were working with bitmaps to start, but runs a little slower when working with movieclips (because it requires the creation of an additional bitmap). The above method also has the advantage that you can run multiple comparisons using the same bitmap, which I have taken advantage of in a CollisionEngine class I wrote that combines shape based collision detection with my grid-based proximity manager to provide the ultimate game-oriented collision system.
UPDATE: The source code is now available here.