“My God… Its full of stars!”
August 7th, 2007 by DC
Have I mentioned how much I like the BitmapData class? Had a request pass by desk last week asking me to create a little app to be used in a presentation. They wanted it so that when a user clicked on a button in the middle, a star would fly across the screen to a random location, twinkling while it moved, then stay on the screen until the user clicked clear. They wanted somewhere between 30 and 100 stars on the screen.
While I think flash could have handled having that many MovieClips on screen pretty easily on its own, I wanted to see if I could make it more efficient. The solution I came up with was to use two BitmapData layers, one for moving the stars on the screen and creating the ‘twinkling trails’ and the other for housing all the stars in their final resting place.
The two layers of BitmapData (trailsCanvasBmp, and finalBallCanvasBmp) and a ParticleManager class to track the movement of the stars and slowly fades out the trailsCanvasBmp to give the twinkling effect while its moving. A star is created in the center of the screen, then shoots off to its random location. When the tween is complete the star is drawn to the top finalBallCanvasBmp class which is never cleared.
On each frame a random pixel is chosen from the finalBallCanvasBmp and if that pixel is NOT black (0×000000), then it attaches an mcTwinkle MovieClip which destroys itself upon finishing its animation.
The effect is really quite cool! You get the sense that each star is operating under its own principles, but its actually just two BitmapData objects interacting with the ParticleManager.
You will notice some major performance hits if you tell it to make too many stars at one time, or if the screen gets literally filled with stars, their may be more twinkling than your computer can handle. We’re on some beefy machines here at work, and I have had over 20,000 stars and haven’t noticed a performance hit. So your movies can truly be “Full of Stars”. ($1 to who ever can name the movie reference*)
There are a few other things going on here that I can elaborate on if requested. The background is generated using Perlin noise (so really there are 3 Bitmaps). Each star is colored using my Pallet class I can upload if desired. Full code for this project can be uploaded.
d.c.Holth