Preventing the bounding box of transparent Bitmap Sprite from triggering mouse events

前端 未结 1 1658
轻奢々
轻奢々 2020-12-22 13:01

I thought I had solved my mouseEvent problem for Sprites containing a Bitmap with an alpha channel but I\'ve encountered a new issue shown in the image below: the bounding b

相关标签:
1条回答
  • 2020-12-22 14:04

    If using a vector mask is not a viable option (it should work if you changed your hitSpite into a Shape and then made it the mask of the map piece sprite - also you'd have to add it as a sibling of the map piece and not a child), then the way most people do this is checking if the pixel under the mouse is transparent or not.

    Here is an example:

    Let's say all your map pieces are the sole children of a Sprite referenced in a var called container. Let's also make the assumption for the example, that your map pieces are all Sprites that have the png Bitmap as the bottom most child.

    You need to add the click listener to the container (instead of each individual map piece):

    container.addEventListener(MouseEvent.CLICK,click);
    
    function click(e:MouseEvent):void {
        var child:Sprite; //a helper var to store the current iterations child below in the while loop
        var target:Sprite; //the item that we determined was clicked
    
        //iterate through all children of container (backwards, so we process the top most layer first)
        var i:int = container.numChildren;
        while(i--){
            child = container.getChildAt(i) as Sprite; //populate the child var
    
            //now we check if the mouse is over this child by a simple hit test point
            //we also then check if the pixel under the mouse is transparent (a value of 0)
            if(child.hitTestPoint(e.stageX, e.stageY) && Bitmap(child.getChildAt(0)).bitmapData.getPixel32(child.x + e.localX,child.y + e.localY)){
                target = child;
                break; //break out of the loop since we found a child that meets the criteria
            }
        }
    
        trace(target);
    
        //now do something with target
    }
    
    0 讨论(0)
提交回复
热议问题