Search code examples
actionscript-3bitmaprotationpixelcollision

Actionscript 3 pixel perfect collision. How to? (learning purposes)


I know that there are people out there creating classes for this (ie http://coreyoneil.com/portfolio/index.php?project=5). But I want to learn how to do it myself so I can create everything I need the way I need.

I've read about BitMap and BitMapData. I should be able to .draw the MovieClips onto a BitMap so I could then cycle the pixels looking for the collisions. However, It's weird and confusing dealing with the offsets.. And it seams like the MyBitMap.rect has always x = 0 and y = 0... and I can't seam to find the original position of the things...

I'm thinking of doing a hitTestObject first, then if this was positive, I would investigate the intersection betwen the movieclips rectangles for the pixel collisions. But then there is also another problem (the rotation of movieclips)...

...I need some enlightment here on how to do it. Please, any help would be appreciated..


Solution

  • I managed to do it after all, and I already wrote my class for collision detections,/collisions angle and other extras.

    The most confusing process is maybe to align the bitmaps correctly for comparing. When whe draw() a movieclip into a a BitmapData, if we addChild() the corresponding Bitmap we can see that part of it is not visible. it appears to be drawn from the center to right and down only, leaving the top and left parts away from beeing drawn. The solution is giving a transform matrix in the second argument of the draw method that aligns the bitmap and makes it all be drawn.

    this is an example of a function in my class to create a bitmap for comparing:

        static public function createAlignedBitmap(mc: MovieClip, mc_rect: Rectangle): BitmapData{
                    var mc_offset: Matrix;
                    var mc_bmd: BitmapData;
    
                    mc_offset = mc.transform.matrix;
                    mc_offset.tx = mc.x - mc_rect.x;
                    mc_offset.ty = mc.y - mc_rect.y;
                    mc_bmd = new BitmapData(mc_rect.width, mc_rect.height, true, 0);
                    mc_bmd.draw(mc, mc_offset);
    
                    return mc_bmd;
    }
    

    in order to use it, if you are on the timeline, you do:

    className.createAlignedBitmap(myMovieClip, myMovieClip.getBounds(this))
    

    Notice the use of getBounds which return the rectangle in which the movie clip is embedded. This allows the calculation of the offset matrix.

    This method is quite similar to the on shown here http://www.mikechambers.com/blog/2009/06/24/using-bitmapdata-hittest-for-collision-detection/

    By the ways, if this is an interesting matter for you, check my other question which I'll post in a few moments.