Extending the State Class
Flex offerers a wide range of utilities to make working with complicated components and applications simpler. One such feature is the use of States. States are often thought of as only visual or GUI related, but in they are perfect for dividing up logic. In my current project I am building a series of learning activities, and some have activities within activities… needless to say it can get complicated quickly. While breaking up the logic into separate components was one option, I didn’t want to have any risk of ‘flashes’ of GUI while pieces are refreshed, moved, or risk messing up data by passing all these pieces around.
I started to build out my activity component using states. One state for when you enter the activity, one for each of the three phases, a cleanup state and finally an exiting state. As I developed the components and created their enterState and exitState functions, as well as many functions only used while in a specific state, I realized that my component was getting to be well over a thousand lines of code and a bit unmanageable. To find the logic pertaining to the current section I was working on, I had to sift through hundreds of lines of code. I decided there had to be a better way… and there was!
I started by creating an AbstractActivityState that extended the State class. This had had any common properties and logic, as well as a bindable “Activity” object. This worked well for accessing the public variables of the activity. The problem came with private variables. While I would have had access to these if I had written all my logic within the Activity MXML, since I was passing the Activity object into my states, they were inaccessible.
There were three solutions I found for this problem:
- Make all the properties you need access to within the state public, and break encapsulation rules.
- Add additional Bindable properties to the the custom state classes and pass in the bindable private variables.
- Create a StateMiniModel that had all the bindable properties I needed and simply pass it to the custom state. This is handy if you don’t want to break encapsulation but have a great many common private variables to be passed to all your custom classes.
To make things even more simple, I added some listeners and protected ‘enter/exit’ classes to be called from within the AbstractActivityState so I when declaring my states in MXML I didn’t need to give it anything other than a name.
No CommentsFacebook Friend Geocoder
I’m very excited about the MapQuest API and all the possibilities it offeres developers for creating mapping applications. I wanted to test the API and sharpen my own skills, so over the past few days I’ve been working on a Facebook geocoding application that will put any of your friends with current locations set on a Mapquest map.
It may be because I’m using a free developers license key, but I’ve noticed a few of the locations aren’t geocoding properly. For example, Roseville MN is turning up Roseville California.
I haven’t submitted the application to the Facebook library yet, but feel free to try it out and post any feedback you have either here or on the application about page.
**Update 10/24/2010: This is totally broken now **
Speaking At FlashMN on Wednesday March 19
I will be speaking on developing MapQuest’s TripPix application (formerly MapMyPix) at the next FlashMN users group on Wednesday, March 19th. For those of you unfamiliar with the FlashMN users group, it meets at 7 on the third Wednesday of each month at Easel Training in Saint Paul.
The talk will include information on building application using the MapQuest Advantage API, AIR and Flex Builder 3.
No Comments"My God… Its full of stars!"
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.
2 CommentsWeb Spinner Revealed
As promised, you can now download the code used for my web spinning projects. There is one fla, and four classes.
I made some modifications to Grant Skinner’s grid based proximity manager to take advantage of an IProximityDetectable interface. For a full explanation on how grid based proximity management works, check out Grant’s original post on the subject. The IProximityDetectable interface has only two methods:
interface IProximityDetectable { public function getPosX():Number; public function getPosY():Number; }
As might be assumed, they retrieve the ‘x’ and ‘y’ position of an object. Why implement this? Well, the original ProximityManager used the _x and _y values of a MovieClip, but my spider web particles don’t actually have any MovieClips. Its just adjusting x and y values of an object in memory, and drawing lines to the new distance. The ProximityManager is used for drawing the lines between particles based on how close they are to each other.
So how do the particles move? Each onEnterFrame the ParticleManager calls the tick function for each particle.
public function tick():Void { canvas.moveTo(x,y); x += xVel; y += yVel; xVel *= drag; yVel *= drag; yVel += yGravity; xVel += xGravity; var f:Number = Math.abs(xVel) + Math.abs(yVel); alpha -= f/__lifeSpan; canvas.lineStyle(2, rgb, alpha); canvas.lineTo(x,y); if(alpha <= 0){ manager.removeSpark(this); } var n:Array = pm.getNeighbours(this); var l:Number = n.length; for(var i:Number = 0; i < l; i++){ canvas.lineStyle(1, rgb, alpha); canvas.moveTo(x, y); canvas.lineTo(n[i].getPosX(), n[i].getPosY()); } }
Each particle starts out with random velocities for x and y. These velocities are added to the x and y position of the particle. Drag is applied to the velocities to slow them down. The drag is set to such a small value in this particular instance that it really doesn’t have much of an effect. Gravity along the x and y axis is then applied to the particle The gravity values are generated randomly when the particle is first created and unlike the velocities, has no baring on its parents value (in the instance of a branched particle). Since gravity is random, it may pull particles up, down, left or right. After all moving is done, the particle uses asks who its neighbors are and draws lines to them.
Speaking of branching, the ParticleManager does a probability calculation for each particle during the onEnterFrame which determines if a particle will branch. Each particle has a chance to branch, so growth can occur exponentially. To keep particles from branching too much, this calculation is ignored if the maximum number of particles has been reached (default to 40).
Once each particle has been moved and had its connections drawn, the entire image is drawn to a Bitmap and color/alpha adjusted to fade away slowly. All and all a pretty neat little effect.
I’d like to move this to AS3 eventually to see if I get crazy speed increases! I’ve put one last experiment below which allows you some control over different variables in the spider webs. Be careful when making adjustments… You can easily give your computer a heart attack.
Web Spinning Goodness II
Made a few small technical changes… May not be noticeable to most. In the previous example, each particle received a random Y axis based gravity. When gravity was negative, it forced the particle up, and positive gravity made it go down. I’ve also added an X axis based gravity to this example, increasing the curvature and randomness of the webs.
One CommentBitmapData + Particles = Fireworks
Made this little app today while working with particles and bitmap data. It combines some of the work from Seb’s particle system, with Grant’s bitmap data used in Varicose-g. I’ll get to posting code examples as soon as I clean it up. Each click makes about a 100 particles, so if its running a bit slow, let me know. Enjoy!
Cartoon Smoke Using Particle Systems
Earlier this week I had the pleasure of attending my first FlashBelt conference and had a great time! If you ever get the opportunity to attend, FlashBelt is definitely worth it!
Seb Lee-Delisle gave a great presentation on Particles for the Non-Physicist. I have worked a bit with particles on my own, but never really understood the possibilities of what a particle system could do. Seb pointed out all the spots on the Plug-in Media website that have particles – way more systems going on there than I expected.
I had a chance to speak with Seb after the session as to how he made the merging borders around the cartoon smoke effects and dripping ooze (from the Plug-in Media main page). He said you needed to have multiple layers of particles. So, when I got home, I downloaded the demonstration files and got to work. Below you can see the results. Its a really cool effect.
The important thing when creating the two layers of particles, is that each layers of particles must have matching properties – only the linked movieclip is changed. You can see that the background particle is darker and larger than the foreground, but they move and grow in unison. This allows the background particle to be the border around the lighter front particles and merge together seamlessly.
My next step is to figure out how to use a particle system to make a MovieClip appear on fire. If you’ve seen my fire effect code, it uses a computationally-heavy method of duplicating, distorting, coloring and fading the MovieClip. I think the particle-system effects could be used to create the fire instead.
One CommentFlickr & Flex
As I said in my previous post, I’ve started working in Flex! So far I have been very impressed! Creating dynamic content and application designs is much more natural and faster. Although I miss the timeline, I question whether a pseudo-designer type such as myself would need Flash at all.
That being said, I’ll divulge some of the details of my first Flex component. For this project I was asked to create a Flex component using AS#, and quickly! I had a few neat ideas but decided to kill two birds with one stone and design a lightbox/gallery type component I could use on my art website.
I’ve never been great at designing databases, and don’t reinvent the wheel when I don’t have to. Yahoo’s Flickr service provided all the tools I needed for managing a gallery: tags, dating, sets, and automatic resizing to multiple formats. Yahoo is also kind enough to give access to their Flickr API services so you can access image data from webservice calls which return XML.
Thanks to ActionScript 3′s new E4X extension, XML is easy. If you have ever tried parsing XML in AS2, you will be very happy with this addition!
The section of this project that I’m going to focus on for this post is the Flickr package I’ve been working on. I will admit that there are probably plenty of other AS3 classes that connect to Flickr, but part of the purpose of this project was to challenge myself and get some experience using webservicee (something we don’t get a to use a lot in e-Learning!).
The Flickr Package currently consists of four classes: FlickrImage, FlickrImageData, FlickrUserData and FlickrUserPhotosData. Each of these correlate to one or more Flickr webservice calls. For example, FlickrImageData takes in a picture id and returns almost all the information that is needed for that image, including title, date, user and the paths to the image sizes. I combined the two webservices because I honestly couldn’t see very many times when one wouldn’t need all the data.
Now one question I’m going to pose to the blogsphere is whether or not it is necessary, good or bad to recreate the variables passed in from the XML. For example, in the FlickrUserData class I have this bit of code:
private function onInfoXMLDataLoaded(event:Event):void { var data:XML = XML(_urlLoaderInfo.data); _userName = data.person.username; _realName = data.person.realname; _location = data.person.location; _photosUrl = data.person.photosurl; _profileUrl = data.person.profileurl; _photosCount = data.person.photos.count; _isLoadedInfo = true; dispatchEvent(new Event(FlickrUserData.LOADED, true, true)); }
I’m just taking all the attributes and variables passed in from the XML and attaching them to hardcoded variables. Is this a good practice or does it waste memory and efficency? I would think that one could create getter methods that access the loaded XML directly, but how would these objects work when passed around? Or if one were to create a clone() function? I like creating the actual variables because its what I’m used to and makes sense, but am open to any discussion saying otherwise.
You’ll notice that the FlickrImageData contains just that, all the data, but doesn’t actually show anything to the user. The FlickrImageData class is simply a model class. The FlickrImage class extends the mx:Image class and is the View for the FlickrImageData. You could potentially use a FlickrImage component anywhere you would create a normal image. You simply pass it the Flickr Image ID and a size (if desired, it defaults to Original) and the FlickrImage class will grab all the necessary data and display the image! This is an example of the most popular design pattern in application development today, the Model View Control (MVC) design pattern.
No Comments



