I am completely in the woods here – i have a sprite with a shape drawn in there (there are two different sprites in the example.) At any given point, I need to get the x and y value of the topmost point of the shape. The sprite does rotate so it’s going to change at any point as well. I don’t even know where to begin here – help?
Share
Looping through all pixels could be rather costly. As a rule of thumb, having the player checking pixels is better, whenever possible. Here’s my approach:
First, we get the bounding rect of the display object. That way we discard any transparent pixel right away. Now, that rectangle already gives you the “lowest” y of the sprite (the upper bound), so now we only have to find the value for the corresponding x offset to get the point we’re looking for. At this point we have to test for pixels, so we need a BitampData object. We only need to draw the visible part of the display object (the area enclosed by
bounds). But since we already know the value for y, a 1 px height will be enough. This BitmapData should allow transparency and we’ll fill it up with transparent black pixels before drawing (so we can detect non-transparent pixels after; here we are considering transparent a pixel whose alpha value is 0 and non-transparent anything else; you could use a threshold instead if you wanted; it would require some minor changes to the code). When drawing, we apply a translation to only draw the part we want, an imaginary “line” of 1 px height along the upper bound, as wide as the object’s bounds.Once we have the BitmapData drawn, we get a rectangle that encloses all non-transparent pixels using
getColorBoundsRect. This rectangle’s x value is the x we were looking for. And now we have both x and y. Those coords are relative to the object visible area (bounds), so we have to offset them with the x and y ofbounds. And that’s the top-leftmost point of the shape within the sprite.But this is an untransformed point, so if you rotate or scale the sprite, this point will not reflect those transformations. Transforming this point is easy, though. Just use the sprite’s transform matrix, to get the point relative to its parent. Or, if you want a global point that takes into account all transformations from this object up to the stage, use the concatenated matrix of the sprite instead.
Edit
A function that does the same as the above but let’s you specify an alpha threshold in the range 0 – 255. It uses the same idea I explained previously, although it’s implementation is a bit more involved.