Lets say you need a hit-zone for a transparent bitmap that matches the images non transparent pixels. What do you do? The answer is quite simple, you find all those pixels that you need and draw a square on top of it. Or so i thought, turns out if you draw a square using
[cc lang=”actionscript”]
shape.graphics.drawSquare(x,y,w,h)
[/cc]
You create a bunch of squares inside shape object and they are not merged, so when ever you move your mouse on top of the hit zone, performance peaks for hit test calculations. The solution i came to use was in Marching squares algorithm. The goal of the algorithm is to provide you with a set of shape outline coordinates that you can use with shape.graphics.lineTo(x,y) to draw the outline you need and fill it.
The library i used is located here
and the code is here
[cc lang=”actionscript”]
public static function getOutline(b : BitmapData, xpos : int = 0, ypos : int = 0, zone : Shape = null) : DisplayObject {
if (!zone) {
zone = new Shape();
}
var points:Vector.=MarchingSquares.getBlobOutlinePointsClockwise(b);
zone.graphics.beginFill(0, 1);
zone.graphics.moveTo(points[0].x, points[0].y);
for (var i:int = 1; i < points.length;++i) { zone.graphics.lineTo(points[i].x, points[i].y); } zone.graphics.endFill(); return zone; } [/cc] Now once you have the shape, there is one more trick you need to do [cc lang="actionscript"] var result:DisplayObject = FieldUtils.getOutline(_bitmapData, 0, 0, null); // create a SimpleButton instance to contain the shape var simpleButton:SimpleButton = new SimpleButton(null, null, null, result); // add the simple button to sprite so that flash understands the presence of the hit zone and reacts to mouse input _hitBoxContainer.addChild(simpleButton); _bitmapData.dispose(); [/cc] if you simply add hit zone to display list and try to listen for events they will not fire, you need to go inception on the button, putting it one level deeper and adding event listeners on the sprite containing the SimpleButton instance

Categories: Blog

Leave a Reply

Your email address will not be published.

Time limit is exhausted. Please reload the CAPTCHA.

This site uses Akismet to reduce spam. Learn how your comment data is processed.