Search code examples
actionscript-3mouseeventcollision-detection

Mouse Click detection only on opaque areas of movieclip


I have movieclips (which in turn have more than 1 movieclips in them ). My requirement is to add a MouseEvent.CLICK event to the parent movieclip. So that an event (MouseEvent.CLICK) is dispatched by flash only if the visually opaque (alpha = 100 %) area has been clicked, otherwise , ignore.

The workaround I do as of now is to create an alpha = 0.05 circle which follows the mousecursor in Event.ENTER_FRAME and do a hittest followed by a PixelPerfectCollisionDetection (courtesy one gr8 guy I admire on google code :) )

In short, I need to know If I can make flash dispatch a MouseEvent only when clicked on a visually opaque area of the movieclip and NOT anywhere in the bounding box region.

Thanks,

Vishnu Ajit


Solution

  • I got this solution. But It's not perfect at all, cause you create everytime a new bitmapData object of your MovieClip:

    myButton.addEventListener( MouseEvent.CLICK, clickFunction);
    
    private function clickFunction(e:MouseEvent) {
        if(pixelIsVisible(e.currentTarget, e.currentTarget.mouseX, e.currentTarget.mouseY)) {
            //DoSomething
        }
    }   
    
    private function pixelIsVisible(target:*, xPos:int, yPos:int):Boolean {
        var bmp:BitmapData = new BitmapData( target.width, target.height, false );
        bmp.draw( target as MovieClip );
        var pixelValue = bmp.getPixel( xPos, yPos);
    
        //Dispose bitmapData to free memory
        bmp.dispose();
    
        var alphaValue:uint = pixelValue >> 24 & 0xFF;
        //alphaValue is from 0 to 255
        if(alphaValue >= 255) return true;
        else false;
    }