Yesterday I mentioned that the BitmapData function copyPixels can be used to combine image data and alpha data from two different sources. This function has a number of uses, in addition to adding transparency to images that don't have any.
copyPixels is a fast blitting function, and ActionScript's only one. It's main function is to copy pixels from one place to another, bypassing the rendering system that draw uses. It is much more limited than draw, but fast.
If that were all it did it would not be very interesting. But it has two optional parameters which extend its capabilities. The main one is the alphaBitmapData, which is simply a BitmapData which is used for the alpha channel of the copy. The other parameter, mergeAlpha, is a Boolean which specifies whether the alpha will be combined with the alpha channel of the image being copied or will overwrite it.
One use I found for it is for creating levels in Bug Tunnel Defense. I cannot share the code for this as it's too long and too tied into the rest of the game, but the principle is straightforward. To represent tunnels the game has two layers. The main game takes place on the top layer but the bugs can escape into tunnels on the layer below.
The layers are Bitmaps with similar BitmapData, assembled by using copyPixels with 60 × 60 tiles. The bottom layer just copies this data to cover the 540 × 540 area. The top layer is constructed similarly except an alpha channel is combined with the data.
When the top layer is placed above the bottom layer they look like one layer, as the colours are the same. But if something is inserted between it shows through in varying amounts depending on the alpha channel added to the top layer, as if the depth of the tunnel varied. This applied to both the tunnels (drawn onto the bottom layer) and the bugs (in a layer of their own between the Bitmaps).
I could have instead just rendered the top layer with alpha less than 1, but that would have meant it had uniform transparency, not varying along the tunnel. In addition walls, bug deaths and other effects are drawn onto this layer. They would have to be done in a separate layer, adding to the rendering cost, if the ground had alpha less than 1.
The reason for doing it this way is it's very fast. It does all of the copyPixels operations for two layers, as well as other setup, in a few frames, so fast that levels seem to load instantly. This is easier to see this in the editor, where colour and tile changes force a full redraw.
So if what you want to do can be done with copyPixels then definitely use it, even if it requires extra setup beforehand. It is so fast it beats other methods by a large margin, and so should be used whenever's possible.
No comments:
Post a Comment