Você está na página 1de 65

Editor’s Note

Greetings readers!
Our magazine has certainly come a long way since its creation as a traditional, print
publication and many factors have influenced the magazine’s growth and development
over the 3 years. The dramatic transformation of the publishing industry has played a
significant role as we’ve moved to a more interactive e-zine format. Now we have another
change for you – Now, we are Monthly! But without question, loyal readers like you have
been the biggest, most influential and most consistent driving force behind the magazine’s
ongoing evolution.
Content has always been the most important for FFD magazine. But now, we’re taking
that commitment to the next level. This starts with even more in-depth, hard-hitting
technical articles, tutorials and other content designed specifically to help you do your job. For example, you’ll find
a regular Special Report section – this issue – Hot topic of the latest – Apple vs Adobe, great article written by Lee
Graham.
It wouldn’t be much of a Flash and Flex Developer’s magazine if there weren’t any ActionScript Developement
articles in it. Also the Components section is full of the greatest articles available; Louis Dicarro shows you how to
create Custom Flash CS4 and AIR components.
Ryan D’Agostino in his article ‘Creating an XML Photo Gallery with AS’ – shows up how to create an ActionScript
application in Flex Builder 3. If you want to create flash games – do not miss our Creating an AS3 Game
Framework series of articles.
We’re listening, and we need your input. Today, more than ever, your feedback directly guides the editorial direction
of the magazine. So please take the time to click the Feedback link, send us your suggestions and help us make FFD
Magazine an even more responsive, reader-guided publication. Thanks again for being dedicated to the growing
community of readers who rely on FFD to help them stay abreast of changes in the technology as well as push the
envelope of what’s possible.

Enjoy.
Ewa Samulska
ewa.samulska@ffdmag.com

Editor in Chief: Ewa Samulska ewa.samulska@ffdmag.com Thanks to the most active and helping beta testers:
Proofreaders: Patrick French, Betsy Irvine Russell TangChoon, Lee Graham, Jassa Amir Lang, Ed Werzyn, Yann Smith-Kielland,
Justus, Csomák Gábor, Kevin Martin, Charles Wong, Ali Raza, Almog Koren, Izcoatl
Armando Estanol Fuentes, Lionel Low, Michael J. Iriarte, Paula R. Mould, Rosarin
DTP Team: Ireneusz Pogroszewski
Adulseranee, Sidney de Koning
ireneusz.pogroszewski@software.com.pl
Art Director: Ireneusz Pogroszewski
To create graphs and diagrams we used program by
ireneusz.pogroszewski@software.com.pl
company.
Senior Consultant/Publisher: Paweł Marciniak
The editors use automatic DTP system
Mathematical formulas created by Design Science MathType™

Publisher: Software Press Sp. z o.o. SK


ul. Bokserska 1 02-682 Warszawa Poland Worldwide Publishing ATTENTION!
Distributing current or past issues of this magazine – without permission of the
Software Press Sp. z o.o. SK is looking for partners from all over the World. publisher – is harmful activity and will result in judicial liability.
If you are interested in cooperating with us,
please contact us by e-mail: cooperation@software.com.pl DISCLAIMER!
The techniques described in our articles may only be used in private, local net-
Whilst every effort has been made to ensure the high quality of the magazine, the works. The editors hold no responsibility for misuse of the presented techniques
editors make no warranty, express or implied, concerning the results of content usage. or consequent data loss.

All trade marks presented in the magazine were used only for informative purposes.
All rights to trade marks presented in the magazine are reserved by the companies
which own them.

03/2010 (11)
4
CONTENTS
Special Report Components
08 The Flash on iPhone War 44 Custom Flash CS4 Components in Flash
BY LEE GRAHAM Builder 4
BY LOUIS DICARRO

InBrief 52 AIR Components in Flash Builder


BY LOUIS DICARRO
10 News

Tools TLF
12 Storyfarm Switches to G-Technology™ 56 Applying CSS to Text Layout Framework styles
G-SPEED™ eS PRO to Cut Latest Doc Projects BY MAXYM GOLOVANCHUK
BY DEAN MERMELL

Profile
Beginners
60 Flashcreed – Business Gallery
14 Working with Display Objects 101
BY JUSTIN P. JUNDA
Books Review

ZEND and PHP 64 Essential Guide to Flash Games


BY ALI RAZA
18 How a Software Flight Recorder was Built
Using Adobe Flex and Zend PHP
BY KEVIN SCHROEDER AND RYAN STEWART

ActionScript Development
Tip of the issue
20 Creating an AS3 Game Framework Setting Individual Compression
BY JEFF FULTON, STEVE FULTON for Audio Files in Flash
32 Creating an XML Photo Gallery with AS3 Joe Laurino – Game Producer/Audio Director, Arkadium

BY RYAN D’AGOSTINO Normally, Flash tends to export all of a SWF’s sounds in MP3
format at 16kbps (and in mono, no less). You’ll get great
compression this way – the �delity though is not so great.
While you can up the quality globally, you’ll get the best
results by setting the compression and output format of
each sound individually. This will allow you to balance �le size
against sound quality with far more precision than you would
get from blanket compression. For example, if there is a sound
The issue 3/2010 sponsored by Advertisers: that’s used frequently, you can set it to use less compression
Influxis FITC so that it sounds cleaner. If you’ve got a sound that plays
www.influxis.com ............................................. 2-3 www.fitc.ca ......................................................... .43
subtly in the background every now and then, you can get
Mediaparts Interactive S.A
www.page-flip.com ............................................. 5
Exsys
www.exsys.com ................................................. .45
away with compressing it a lot more. To compress sounds
individually, open the Library by clicking Window>Library.
Digicrafts Infosoft Global (P) Ltd.
www.digicrafts.com.hk ...................................... 7 www.infosoftglobal.com .................................... 47 Select the sound you wish to tweak, and navigate to
Kevin Ruse + Associatess Inc. Flash and Math ‘Properties’ in the Options menu. You’ll see a drop down list
www.kevinruse.com .......................................... 19 www.flashandmath.com .................................... 55
there that’s set to ‘Default’ initially. Earlier versions of Flash will
Kindisoft
www.kindisoft.com ............................................ 31
Creativeniche
www.creativeniche.com .....................................59
have to stick with ADPCM, but otherwise you should go with
MP3 for best results. I’ve found that 80kbps or 112kbps tends
Flex{er} ActionScriptJobs.com
www.flexer.info ....................................................33 http://actionscriptjobs.com .................................65 to work best when compressing MP3 �les, but I suggest you
Gamersafe Electricrain try a few to see which best suits your project.
www.gamersafe.com ......................................... .35 www.erain.com ...................................................66

03/2010 (11)
6
SPECIAL REPORT

The Flash on iPhone War

The Preface...
Since the beginning of the year, I’ve been a part
of Adobe’s Flash CS5 beta program, using
CS5 and AIR 2 to develop a simple eBook
application TheProducer (Lite Edition
http://itunes.apple.com/us/app/theproducer-
lite-edition/id354580730?mt=8), which was
approved and accepted into the iTunes Store.
As of April 24th, Apple hasn’t pulled the app...
yet.

Bad Apple…
As many have heard, Apple’s new iPhone OS
4.0 SDK Beta Agreement, Section 3.3.1 states,
Applications may only use Documented APIs in the
manner prescribed by Apple and must not use or call
any private APIs. Applications must be originally written
in Objective-C, C, C++, or JavaScript as executed by
the iPhone OS WebKit engine, and only code written • Lee Brimelow, a well known Flash Evangelist
in C, C++, and Objective-C may compile and directly for Adobe said Go screw yourself Apple
link against the Documented APIs (e.g., Applications (http://theflashblog.com/?p=1888). on his personal
that link to Documented APIs through an intermediary blog.
translation or compatibility layer or tool are prohibited).
You can read the full post on DaringFireball.net Google’s response…
Andy Rubin, VP of Engineering for Android, weighed
The Issue... in on the situation, fully backing Adobe (http://
Apple has created an uproar among developers using blogs.adobe.com/conversations/2010/04/adobe_
3rd party tools such as Unity, Appcelerator’s Titanium air_on_the_android_platf.html), Google is happy to
and, yes, the much anticipated Adobe Flash CS5 be partnering with Adobe to bring the full web, great
iPhone Packager. The timing of Apple’s new agreement applications, and developer choice to the Android
couldn’t have come at a worse time, just days before platform. Our engineering teams have been working
the Adobe CS5 Launch. closely to bring both AIR and Flash Player to Google’s
mobile operating system and devices. The Android
Adobe’s response thus far… platform is enjoying spectacular adoption, and we
expect our work with Adobe will help that growth
• Kevin Lynch, CTO at Adobe did a video interview continue.
(http://kara.allthingsd.com/20100411/exclusive-
video-adobe-cto-lynch-smacks-back-at-apples- As a Flash/Flex Developer...
protectionist-strategy-calling-it-bad-for-consumers- There is so much potential with Flash CS5, Flash
but-hell-swing-chickens-if-forced/) with All Things Builder 4 and AIR 2. Adobe’s Open Screen Project will
Digital. put Flash/AIR on as many devices, including desktops,
• Mike Chambers, a Product Manager for Adobe, mobiles, tablets and HD television sets. And, there is a
recently made a post on his personal blog (http:// fast growing Facebook Group (over 10,000 members),
www.mikechambers.com /blog /2010 / 04/20 /on- called I’m with Adobe! (http://www.facebook.com/group.
adobe-flash-cs5-and-iphone-applications/). php?gid=113492765344092).

8 03/2010 (11)
The Flash on iPhone War

Current events… Due to the flexibility of Android, it is easy to install apps


In the past few weeks, it appears that Apple is still from a variety of methods: download from URL, USB
approving apps built with 3rd party tools, while not connection, MiniSD card, or the Android Market (http://
approving those developed with the Flash CS5 iPhone www.android.com/market/). No syncing needed.
Packager. As Mike Chambers stated in a recent blog
post (http://www.mikechambers.com/blog/2010/04/ Timeframe of AIR for Android...
20/on-adobe-flash-cs5-and-iphone-applications/), While Adobe has not yet stated a release date for
Developers should be prepared for Apple to remove this upcoming tool, developers can stay informed by
existing content and applications (100+ on the store signup at the Adobe AIR for Android Beta Notification!
today) created with Flash CS5 from the iTunes store. (https://www.adobe.com/cfusion/entitlement/index.
cfm?e=labs_air_android_signup).
Moving forward…
While the future of Flash/AIR on the iPhone and iPad Future of Android Platform…
remains problematic, the situation has given birth to Over the next several months, there will be a
a very exciting and new AIR 2 developer tool, AIR for number of new Android mobiles and tablets hitting
Android (http://blogs.adobe.com/air/2010/04/adobe_air_ the market this summer. Personally, the tablet that
applications_for_and.html)! There are many from the has me most excited is Notion Ink’s ADAM (http://
Flash CS5 beta (including myself) that have ported www.notionink.in/adamoverview.php), but there are
our Flash CS5 iPhone and iPad Apps successfully to others as well, including the Marvell Moby, WePad
the Android OS. For me, I simply tweaked a couple of (http://www.marvell.com/company/news/press_deta
graphics, resized, compiled and installed directly to my il.html?releaseID=1397 custom version of Linux that
Nexus One. supports Android, Flash & AIR apps), Dell Mini 5 (http://
gizmodo.com/5443837/first-hands+on-and-video-dell-
The excitement!!! mini-5-android-slate), to mention a few.
The Android App Market is growing faster than any other
app market currently out there, partly due, I believe, to Don’t Forget…
the fact that Google has created the OS as an open While you can develop Flash, Flex and AIR apps for
source platform, a truly creative environment for the desktops, laptops, netbooks, and Android, Adobe also
developer community. As analyst James Governor put plans to bring AIR 2 and Flash Player 10.1 to Palm webOS,
it (http://twitter.com/monkchips/statuses/12511502233), Windows Phone 7 and BlackBerry RIM devices. In
[The] company doing [the] most to grow the Android app addition, Adobe’s Slider (Flex 4 Mobile Framework http://
base is Apple. The new terms of service are AWESOME labs.adobe.com/technologies/flex/mobile/) targeted to
for the Android team.... run on high-end smartphones (phones with a processor
speed of 400Mhz or more and 128MB of RAM) is also
My experience with AIR for Android… scheduled to be available in 2010!
It is quicker to develop, and easier to deploy, giving you
more time for other things. Bottom Line...
It’s going to be a fabulous year for developers building
Building an iPhone App (with or without Flash CS5) Android apps using Adobe Flash CS5 and AIR 2!
Click here to view a few videos AIR on mobile devices:
1.Go to the Apple’s Developer Portal http://www.adobe.com/devnet/devices/demos/
2.Code your app BREAKING NEWS
3.Create a distribution certificate Click here to read Steve Jobs, CEO of Apple, direct response
4.Then you need to create a mobile provisioning file on why Apple isn’t including Flash on the iPhone and iPad:
for the app http://www.apple.com/hotnews/thoughts-on-flash/
5.Compile
6.If all went well, you drag and drop your mobile Here is Lee Graham response to Steve Jobs’ post:
provisioning file and iPhone app into iTunes http://l33.me/apples-ceo-entered-an-insanity-plea-as-the-re
7.Finally, sync your iPhone/iPad with iTunes
LEE GRAHAM
With AIR for Android Lee Graham is co-founder of TRImagination (http://
trimagination.com/), an educational app company based in
1.You simply code your app the United States. He has been involved in creating interactive
2.Compile eLearning programs for �ve years and working with Adobe in
3.Install the app. Done. beta testing Flash CS5, AIR 2 & AIR for Android.

03/2010 (11) 9
IN BRIEF

Adobe Online Developer Week,


May 10-14 PDF Navigator developer con-
During Developer Week, learn
about the Adobe Flash Platform, test could get your
including Flex, Flash Builder, AIR,
and how it integrates with Cre- Flex/Flash resume in front of
ative Suite 5 technologies. This
week-long event features free,
live webinars presented by Adobe
leading RIA & brand agencies
AcrobatUsers.com has launched the Acrobat PDF Portfolio Navigator con-
technology experts. See live demos test. Flex developers create custom navigators using Flex and the Acrobat
and have your questions answered
by the experts during interactive
ActionScript API. The top three entries win great prizes. The top ten get
Q&A sessions. Register and attend their Flex/Flash portfolios in front of some of the top brand, RIA and user
whichever sessions suit your needs experience design firms in the world: G2, Blitz, Catalyst Resources, Effecti-
and you will be eligible to win a ve UI, and Universal Mind.
copy of Flash Builder 4 Professional Its a win win situation. The Adobe-sponsored Acrobat User Communi-
or Creative Suite 5 Web Premium. ty gets examples of innovative PDF Navigators. Flex developers get the
For more info, and registration,
chance to show off their create and technical work to the people who are
visit http://www.adobe.com/cfusion/
event/index.cfm?event=detail&i- looking for great and creative Flex developers. Adobe will also feature the
d=1489921&loc=en_us top ten entries on the Adobe.com website.

from webkitchen.be The contest runs now through June 7, 2010.


Full contest details are at http://www.acrobatusers.com/navigator-contest
Adobe Flash Platform on android

Flash Builder, Flex 4 and Cold-


If you want to know when Flash Player
10.1 and AIR 2.0 becomes available for
Android go to adobe.com, and sign
up for the noti�cation! The promises
say, it’ll come in H1 of 2010! fusion Builder released
On the morning of march 22nd, Adobe removed the beta versions from Ado-
from corlan.org
be Labs and added downloads for shipping versions. If you’ve wondered if
Apple Slaps Developers you’ll want to upgrade your Flex Builder to Flash Builder - trust us - you real-
In The Face ly should! Flash Builder, which is now part of Creative Suite 5 Web Premium
The new iPhone 4.0 SDK modi�ed the and Master Collection, is a joy to use and the new Flex SDK solves a lot of
terms of use, so now creating appli- issues developers have had.
cations in any non-Apple-approved
languages is a violation of terms.
This does not just affect Adobe but
also other technologies like Unity3D.
Apple announced this right before
Flash CS5 came out, with the -now
useless- iPhone packager.
“Now let me put aside my role as an
official representative of Adobe for a
moment as I would look to make it
clear what is going through my mind
at the moment. Go screw yourself
Apple. “
“I believe that we have witnessed The price of the software are:
a deliberate smear campaign aga- Flash Builder 4: Standard: $249 (upgrade: $99), 4 Premium: $699
inst Flash to drive content providers
towards improved web browsing
(upgrade: $299), Coldfusion Builder 1: $299 (upgrade: n/a)
support for iPhone OS devices. A
purely competitive measure driven to Some new features of FB4:
ensure that Apple devices can appear
to compete with impending releases • Improving designer/developer workflow
of Android that include Flash Player • Enabling data-centric development
10.1.” Mark Doherty
• Data/service modeling and binding made easy
from the�ashblog.com, �ashmobile- • Advanced data management features
blog.com
from flashmagazine.com

10 03/2010 (11)
IN BRIEF

Flash is as open as HTML5 Flash Player and Google’s


Chrome integration
From now on, when users download
Today, the hottest topics in Flash news are in connection with Apple, and
Chrome, they will also receive the
HTML5. Serge Jespers wrote a same titled post on his blog about his opinion in latest version of Adobe Flash Player.
this topics. Here are some toughs from it: This is not a fight. HTML5 and Flash There will be no need to install Flash
can live together just fine and can even complement each other! On AppleInsi- Player separately.
der, an Apple spokeswoman claimed that Mike Chambers got it all backwards Users will automatically receive
when he blogged about Apple’s closed system. That’s not the part that made updates related to Flash Player
using Google Chrome’s auto-update
me cringe though. She said that “it is HTML5, CSS, JavaScript, and H.264 that
mechanism. This eliminates the need
are open and standard, while Adobe’s Flash is closed and proprietary“. to manually download separate
H.264.is far from open. It is owned by a private organization known as updates and reduces the security risk
MPEG LA who said earlier this year that “Internet Video that is free to end of using outdated versions.
users would continue to be exempt from royalty fees until at least December With Adobe’s help, we plan to further
31, 2015“. Nobody knows what is going to happen after 2015. protect users by extending Chrome’s
So what about HTML5, CSS and JavaScript… Those are open, right? “sandbox” to web pages with Flash
content.
Well yeah. The specs are open meaning that everyone can download tho-
se specs and build an application around it to display that language. Hey… from corlan.org
Wait a minute… That sounds a lot like Flash! The specs for FLV (Flash
video), SWF (the file format for Flash Player), AMF (the binary format for Brand new Flex.org
exchanging data) and RTMP (the protocol used for transmission of audio, Those of you familiar with Flex.org
will notice a substantial difference!
video, and data) are all published and can be downloaded by anyone.
Be sure to check out the new Flex
The specs for HTML5 are decided by the Web Hypertext Application Techno- showcase (click “What’s Possible“).
logy Working Group (WHATWG). The WHATWG was founded by individuals of Every time they add an application
Apple, the Mozilla Foundation, and Opera Software in 2004, after a W3C work- to the showcase, they tweet it on
shop. Apple, Mozilla and Opera were becoming increasingly concerned about http://twitter.com/�exshowcase so
the W3C’s direction with XHTML, lack of interest in HTML and apparent disre- follow them!
Now when you want to show your
gard for the needs of real-world authors. Anyone can participate as a Contribu-
boss, friends and co-workers what
tor by joining the WHATWG mailing list. The same goes for Flash. The bugbase Flex is about, you have a good place
is open to anyone and anyone can view bugs and add feature requests. But the to send them for a quick introduc-
Flash runtime is closed! Ok… Sure… Flash Player is not open source although tion.
some parts are. That said… Ask yourself this: Is your browser open source?
The only browser that is completely open source is Firefox. Safari is only partly from gregsramblings.com
open source (only the WebKit engine). The same can be said about Chrome
(in the Chromium project). However, the biggest HTML runtime out there –Inter-
net Explorer (still used by over 50% of all internet users)– is as closed as Flash
Player. And so is Opera (even though they are part of the WHATWG).
And with that, I come back to the title of this post: Flash is as open as
HTML5 = HTML5 is as open as Flash.

from webkitchen.be
Flasher Magazine Issue 3 by Lee
Adobe Creative Suite 5 Announced Brimelow
Lee Brimelow, Platform Evangelist
On April 12th, Adobe released Creative Suite 5, the next evolution of Adobe at Adobe released the 3rd issue of
products delivering a huge amount of new technology and innovation for de- Flasher Magazine and you can watch
it on his blog: http://the�ashblog.com/
sign and development on the web, print, video, photography and extending ?p=1942
the creative workflow with Omniture Analytics. With the new suite of tools
we have delivered Flash Player 10.1 for the creation of web content across from the�ashblog.com
platforms, including mobile smartphones.

Some new features of Flash CS5:


• New text engine • Video improvements
• XML-based FLA files • Streamlined development environment
• Spring for Bones • Integration with Adobe Flash Builder News selected by Gábor Csomák
• Deco brushes • Omniture integration

03/2010 (11) 11
TOOLS

Storyfarm Switches to
G-Technology™ G-SPEED™ eS PRO to Cut Latest Doc Projects

San Francisco-based post house sold on product’s speed,


capacity, scalability and responsive tech support

V
ideo editors working in high definition (HD) face Benefits
increasing technical challenges on a daily basis. Speed and scalability. Dean had reached a point at
Their tools need to be sharp, fast and function his company where he couldn’t afford to compromise on
well under deadline. The sheer size of video files that performance any longer. While Dean doesn’t work much
have to get pushed through today’s postproduction with uncompressed video, he does use a lot of layers,
workflows can slow a system down to a level where composites and effects at 720 and 1080 resolutions,
the creative process just isn’t fun anymore. For an so he needed the same kind of throughput as editors
editor working in HD, the external storage solution that working with uncompressed 2K files.
holds your video is now as important as your camera, The G-SPEED eS PRO was appealing to Dean
computer and editing software, and the last thing any because not only did it suit him for the work he’s doing
editor wants is to have issues because their workstation now, but if he wanted to work on uncompressed or 2K
can’t deliver the goods. projects in the future, he liked the idea of simply adding
another G-SPEED eS PRO to the system, which is
The Story Behind Storyfarm much cheaper than moving up to fibre channel.
Storyfarm (http://www.storyfarm.com/) is a post- A single, four-drive G-SPEED eS Pro unit in RAID 0
production shop based in San Francisco. Owner, Dean delivers a data transfer rate of up to 424MB/sec read
Mermell, cuts long-form documentaries, corporate and 406MB/sec write performance.
promos and TV commercials for a wide range of clients When two units are connected together in fail-safe
in the greater Bay Area. He’s written for DV magazine RAID 5 using the included PCIe RAID controller card,
and Macworld and taught Final Cut Pro® and digital the performance goes up to 678MB/sec read and
filmmaking at Stanford University. In his free time, Dean 730MB/sec write.
writes, produces, Capacity. Knowing that the current 3.5-inch G-
directs and scores Technology product line utilized Hitachi’s latest 2
contemporary terabyte (TB) Deskstar drives, Dean decided the 8TB
silent films. His G-SPEED eS PRO would best meet his needs. While
silent short, eight terabytes seemed like a lot of space at first, Dean
Modern Life, sometimes has two or even three client projects going
won the 2000 on at once, as well as his own creative work, and
San Francisco he quickly found that the hours of 1080 data he was
International Film working with added up fast.
Festival's Golden
Gate Award for Great Tech Support
best short film. You can have the best hardware at your disposal, but
if you can’t get the help you need when you crucially
The Solution need it, it’s not worth anything. When configuring the G-
G-Technology G- SPEED eS PRO, Dean quickly discovered the value of
SPEED eS PRO a responsive technical support staff.

12 03/2010 (11)
Storyfarm Switches to G-Technology™ G-SPEED™ eS PRO to Cut Latest Doc Projects

The G-SPEED eS PRO is striped in RAID 0 right out the Panasonic HVX 200, JVC’s HM100 and even an
of the box, and it was wicked fast, but like many editors old Sony PD150.
do these days, Dean really wanted to format it in RAID At the end of each production day, David overnights
5,. He called tech support and immediately spoke to Dean the P2 files on a small FireWire drive, which
a person who was very knowledgeable about the G- Dean copies and unpacks onto his G-SPEED eS PRO
SPEED eS PRO drive and how different RAID levels before overnighting the drive back to the filmmakers.
work overall. Links to trailers and clips for both of these projects
can be found on Storyfarm’s Projects webpage
Additional features of the G-SPEED eS Pro include: (http://www.storyfarm.com/mainfolder/StoryfarmProjec
ts.html).
• RAID 0, 1, 3, 5 and 6 – easily configurable and The external storage solution Dean used prior to his
managed via a browser-based GUI work with David and Susan worked fine for standard
• Single unit supports multi-stream compressed HD, definition projects that didn’t come with punishing
ProRes 422 and single stream uncompressed HD deadlines. However, when The Trouble With Normal
playback landed in his lap, he soon found that his current solution
• Super quiet desktop unit with very small footprint just wasn’t up to the task in terms of reliability and
• Two units support dual-stream HD playback and performance.
a single stream of 2K The video bit rate for this project comes in at around
• Professional, locking mini SAS port with mini SAS 5.9MB per second, which my previous RAID could
cable included handle without a problem, said Dean. But for this
• Storage capacities available up to 8TB per unit, particular project, and the way it’s being cut, the amount
scalable to 16TB of layers and filters, not to mention the sheer volume of
• Compact and stylish aluminum enclosure with data, brought my old system to its knees.
thermo-regulated cooling fans Dean researched the G-Technology by Hitachi product
• Hot-swappable disk drive modules line and decided the G-SPEED eS PRO configured in
• Formatted HFS+ mounts on a Mac Pro desktop RAID 5 had the speed, security and capacity to meet his
right out of the box workflow needs.

Going Beyond Normal What’s Next for Storyfarm?


Dean’s current documentary project, The Trouble Dean hopes to complete The Trouble with Normal in
With Normal, is about the peculiar state of the modern 2010, get attention through the usual festival channels
mental healthcare system and what it means to be and gain a greater audience through HBO or another
crazy. Filmmakers David Mackenzie and Susan such entity. The Next US is already online, with several
Perkins of Everyday Wonder Productions (http:// moving episodes.
www.wondereveryday.com/) shot the project in cities all Of course part of what has really made these projects
over North America, using a Panasonic HVX 200 set up fun for me is having a rockin’ system that doesn’t slow
to capture in DVC PRO HD24/720P. my creative process. And, in addition to my Mac, I have
Dean’s editing takes a colorful, non-linear approach the G-SPEED eS PRO to thank for that.
that reflects the content of this non-traditional
documentary.
I’ve been using a lot of layers, speed changes and
effects that really push the boundaries of long form
editing to try and communicate the emotional content of
the film. It really maxed out my previous system, but the
G-SPEED eS PRO is handling it with ease.
DEAN MERMELL
The Next US Project Digital �lmmaker, teacher, composer and video editor
Dean is also working with Everyday Wonder on
The Next US project, an ongoing series of 5-minute Martin Landau and Dean
Webisodes that profile small businesses in America that Mermell holding their awards
are thriving in this supposedly bleak economy. for lifetime achievement
David and Susan are currently travelling across and best editor, respectively,
the country in an RV that’s outfitted with a mobile which they received at the
production studio. The project is being shot using California Independent Film
a number of different cameras and formats, including Festival.

03/2010 (11) 13
BEGINNERS

Working with
Display Objects 101

No matter what you do in Flash you will encounter display


objects at some point. So what exactly are display object?
Adobe lists the following definition from their live docs.

What you will learn… What you should know…


• the basics of how to create and manipulate Display Objects • doesn’t need and prerequisite knowledge when it comes to
• use the visual way by dragging from the library tutorial
• add Display Objects to the stage using only AS3 code

T
he DisplayObject class is the base class for all Note* if you already understand this process please
objects that can be placed on the display list. The feel free to skip ahead, if not we will go step by step
display list manages all objects displayed in Flash for the first MovieClip then skip certain sets in the
Player or Adobe AIR. Use the DisplayObjectContainer subsequent examples.
class to arrange the display objects in the display list.
DisplayObjectContainer objects can have child display Go to File => Import => Import to Library.
objects, while other display objects, such as Shape and
TextField objects, are leaf nodes that have only parents and
siblings, no children (http://livedocs.adobe.com/flash/9.0/
ActionScriptLangRefV3/flash/display/DisplayObject.html).
The DisplayObject class supports basic functionality
like the x and y position of an object, as well as
more advanced properties of the object such as its
transformation matrix.
DisplayObject is an abstract base class; therefore,
you cannot call DisplayObject directly. Invoking new
DisplayObject() throws an ArgumentError exception.
All display objects inherit from the DisplayObject class.
So what does that really mean? Well I like to refer to
display objects as any visual on the stage hence the
name display. So therefore I call them visual objects
interchangeably throughout this article.
A visual object can be a MovieClips, Sprites, Text
Fields, Shapes, Buttons etc… again all visual items that
reside on the stage.
So let get started and learn how to import the objects
to the library, we will be using the example files that
accompany this lesson, feel free to use any file that you Select the justin.jpg. This will bring the image into the
want to follow along with. library

14 03/2010 (11)
Working with Display Objects 101

(Note* this name can be anything you want). I typically


use _mc, _btn etc… behind the name for two reasons,
the first being it lets me know easily what type of object
I’m using and the second it enables code hinting in
Actionscript by using the underscore prefix (_mc). Also,
make sure you registration point is set to the upper left.
This is reference point for the MovieClip.

There are two way to access these objects the first way Once you have done that select your newly created
is to drag the justin.jpg image out from the library to the MovieClip instance on the stage and give it an instance
stage name, I called the instance the same thing I named the
MovieClip, justin_mc
Now we can then access its properties via Actionscript.
If you not familiar with instance names this simply is
a way for you to tell Actionscript which item you are
referring to.
Create a new layer and label it actions and lock the
layer.
Now you will need to convert this image into a MovieClip
which is a Display Object. You do this by going to
Modify=>Convert to Symbol

Select the first frame and


open the actions panel,
Window=>Actions

The first properties we


are going to manipulate in
the Display Object a.k.a.
MovieClip is the location
parameters x and y.
These are going to be set
in the upper left corner
where you registration
point was set up. Enter
the code into the actions
This will pop up a dialog box. These settings will be panels
for your new MovieClip. Give it a name of justin_mc
justin_mc.x = 0;
justin_mc.y = 0;

If you test the flash movie you will get something that
should look like this.

03/2010 (11) 15
BEGINNERS

Good now you can play around with the values and
change them to see where other x and y values will
place the MovieClip. The images shown here are with
the x and y set to 200.

Ok congratulations
you have successfully
added a display/visual
object to the stage and
manipulated it. Pretty
Simple.
Now lets delete the
MovieClip from the
stage and access it only
through Actionscript.
Once you have
deleted the MovieClip
off the stage go to the
Library panel and right
click the justin_mc and
select properties.

Select the Export for Actionscript option. The name


you see here will be the name that you create the
object from in Actionscript. This name can be anything
Lets try to access some different properties types but we will keep it the same as our instance name for
enter the following code into your actions panel. no other reason but consistency.

justin_mc.scaleX = 1.5;
justin_mc.scaleY = 1.5;
If you test the movie you will now see that an output
of the justin_mc MovieClip is 1.5 larger that before.
Your image might be pixilated since it’s stretching it to
a larger dimension.

16 03/2010 (11)
Working with Display Objects 101

Once you select the OK button you will get a window selecting it and on the stage and then adding it via
that looks like this. Just select OK. the properties panel like we did before, justin _ mc
references the library class name that you set earlier
within the properties.
and the = new justin_mc(); creates a new instance of
a MovieClip name justin_mc(); and assigns it to the
variable.
The addChild(anyName); just tells Flash to add the object
to the stage using the variable (var) reference that
you just created. If you don’t use the addChild(name of
So if we test our code now we will get and error because variable) you will not see your visual object show up on
we have yet to create a MovieClip and add it to the the stage.
stage. So as you see it’s really not that difficult to access
a display object and display it.

Listing 1.

So delete all the code you have currently in the actions // Creates Instance of the MovieClip named justin_mc
panel. We will first create a variable that will hold the var anyName:justin_mc = new justin_mc();
newly created instance of the MovieClip from the library
instead of dragging it to the stage like we did before. // Set properties for the MovieClip properties
Enter the following code: can be things like rotation,
x y coordinates, Scale sizes
var anyName:justin_mc = new justin_mc(); etc...
addChild(anyName); anyName.x = 100;
anyName.y = 100;
anyName.rotation = 45;
anyName.scaleX = 1.5;
anyName.scaleY = 1.5;

// Assigns the movie clip to the stage


addChild(anyName);

Finally, we will adjust some of the properties just as


we did before. Except this time we use the variable
the var keyword creates a variable anyName. Note* name, that was called anyName. Again, this is just like
as the name states this can be called any name your instance name see (Listing 1).
you want it to be e.g. Bob, Billy, Susan or whatever. In next months issue we will continue this expedition
This is essentially its instance but in code instead of of display objects, and touch on things like drawing
shapes using only code, and working with text. I hope
you enjoyed this article please feel free to email me
your comments or questions to jundaj@gmail.com.

JUSTIN P. JUNDA,
Is a New Media Engineer, specializing in Flash/AS2-3, Photo-
shop, After Effects, PHP, MySQL and a slue of other program-
ming languages. Justin also loves to travel and has a strong
passion for teaching others how to use these technical pro-
ducts. He currently works with a top government-contracting
�rm; implementing new media ideas into interactive course-
ware that is then delivered to the military in order to effecti-
vely train them. Also, check out shpro.tv to see the latest video
from him and his partner Director Scott Hansen wavelenght-
fx@mac.com. You can reach Justin at jundaj@gmail.com with
any thoughts or concerns you have regarding this article.

03/2010 (11) 17
FLASH AND PHP

How a Software Flight


Recorder was
Built Using Adobe Flex and Zend PHP
You might have caught a recent webinar, How Zend used
Flex and PHP to build a Software Flight Recorder, which
sparked some interesting discussion.
How Zend Used Adobe Flex and PHP “Zend Framework with Support for Action Message For- How to build Rich Internet Applications using
to Build a Software Flight Recorder mat (AMF) Now Bundled with Adobe Flash Builder 4” Zend PHP and Adobe Flash Platform..

T
he webinar, hosted by Ryan Stewart, Platform execution of an application – in production or in a test lab
Evangelist at Adobe, and Kevin Schroeder, – and pinpoints root cause issues without trail and error.
Technology Evangelist at Zend, hit the Web around This feature, called Code Tracing, is akin to a software
the same time that Zend announced Code Tracing had been flight recorder for PHP web applications.
added to its PHP web application server. Who, you might Code Tracing can be activated to automatically capture
ask, is this company called Zend? And what is an article problems in real-time, or used manually to trace specific
about flight recorders doing in Flash & Flex Magazine? After scenarios. Zend had strict requirements for the Code
all, you’re a Flex developer, so why should you care? Tracing user interface:

Who is Zend? • The performance chops to handle megabytes of data


PHP runs a third of the world’s Web sites and has now • A highly-interactive view for an exceptional user
become the most popular language for building dynamic experience
Web applications. Zend Technologies, Inc. is the leading • The ability to modify widget behavior
provider of products and services for developing, deploying • Established cross-browser support
and managing business-critical PHP applications. • Sufficient and accessible technical content and
Zend contributes to Zend Framework (an open source, expertise see (Figure 1)
objected-oriented Web application framework), and now
Zend Framework is bundled with Adobe Flash Builder 4. Zend considered various alternatives and ultimately
chose Adobe Flex for the following reasons:
What is a Software Flight Recorder?
When something goes wrong with an airplane in flight, • Performance
investigators obviously can’t reproduce the problem. • Flexibility
Instead, they rely on data captured by the airplane’s • Maturity
black box flight recorder in order to uncover the source • Flash Builder 4 support for data-focused applications
of the problem. Zend Server does the same for PHP
web applications. Rather than trying to recreate the Why Flex developers should care:
environment and reproduce the steps leading up to
a problem, Zend Server captures in real-time the full • Adobe Flash Builder now has built-in support for Zend
Framework, a PHP framework based on PHP 5
• PHP provides easy integration with back-end logic
using Flash remoting
• Zend Server is a data-centric web application
server and Code Tracing helps improve
development and deployment in high performance
production environments.

EXCERPT FROM WEBINAR BY


Figure 1. Flash and PHP KEVIN SCHROEDER AND RYAN STEWART.

18 03/2010 (11)
ACTIONSCRIPT DEVELOPMENT

Creating an AS3 Game


Framework
Excerpted from the book The
Essential Guide to Flash Games:
Building Interactive Entertainment
PART ONE with ActionScript by Jeff Fulton,
Steve Fulton (FriendsofED/Apress,
2010).

T
he game framework is the foundation for making construct containing a set of state constants to switch
the second game. It is an expanded version of the framework between states. States are handled by
the first chapter’s framework with an emphasis state functions inside the GameFrameWork.as file. We will
on organization and reuse. Since this book is also not employ a variable to reference the current state function.
called Proper Object-Oriented Design Patterns and The game timer will use this reference to call the current
Principles for Games, you will see little theory here state function on each frame tick. We will create states
and mostly practice. Many of these techniques have for such things as the title screen, instructions screen,
been hard won and developed over many years of game play, game over, and more.
ActionScript programming. We have fought the wars When we create a new game our document class
through AS1, AS2, and now AS3, so you don’t have to will be an instance of GameFrameWork called Main.as. This
do it yourself. Main.as will have an init (short for initialization) function
While our framework borrows from some design that will set up the framework for use. This Main.as class
patterns, we feel that games are a very expressive will also act as a sort of message gateway between the
medium. We want you, the reader of this book, to game and the framework classes. If you are confused,
think outside that proverbial, over-used box. While don’t worry; we’ll be explaining this in greater detail
design pattern ideas lend themselves to all manner soon.
of application development, we don’t want you to feel
hemmed in to using any one set of ideas for creating The FrameWorkStates.as class
their games. Our framework gives structure to the This FrameWorkStates.as class will simply contain a set of
overall flow of a game but does not dictate how to code constant integer values representing the state machine
the actual game logic. states. When we first create the framework we will have
10 different state constants. All will begin with the STATE_
Exploring the Framework SYSTEM designation. For example, we will have a state
The game framework is housed in a reusable package that displays the title screen. The state constant for this
structure. A package structure at its very basic is an will be STATE_SYSTEM_TITLE. More states will be added as
organized set of folders that will contain reusable we progress through the chapters in this book.
classes. All of the standard class files for using the
framwork will be in this package structure. We will The BasicScreen class
update and extend this structure as we proceed through and SimpleBlitButton helper class
this book. Let’s start by giving you an idea of what The BasicScreen class will be used to display very simple
classes we will be creating for the framework. game state screens. These screens can have a basic
background color with transparency (if needed), as well
The GameFrameWork.as class as some text centered on the screen. Each screen can
The GameFrameWork.as class is the foundation of the also have a button that needs to be clicked to move
framework. It contains a simple state machine and to a new state in the state machine. This class is so
a basic game loop timer. Our state machine is a simple simple that it will probably never be used without major

20 03/2010 (11)
Creating an AS3 Game Framework

modification in your own commercial games. We present We will also be creating three distinct custom event
it here, in its very simple form, for utility purposes. classes as part of the framework. These will be used
The SimpleBlitButton helper class is used to create to send specific data from the Game class instance to the
a clickable button with rollover and off states. The Main.as (GameFrameWork.as instance) class. The Main.as will
button is created completely in code with a simple act on the data sent and if needed, pass the data to
color background for the over and off states to be sed other framework classes. By doing this, we are using
in the BasicScreen class. We do this for simplicity and Main.as as a sort of message gateway.
to demonstrate some Sprite blitting techniques (much
more on these later in the book) using a set of BitmapData The CustomEventButtonId.as class
instances for the background color change of the button This custom event will have the ability to pass an
on rollover. identification integer value to the listening function.
It is used for cases where multiple buttons share the
The ScoreBoard class and same listener function. It will be used in the framework
SideBySideScoreElement helper class (specifically in the GameFrameWork instance, Main.as) to
The ScoreBoard class displays information for the user allow BasicScreen instances to each share the same
during game play. Data such as the current game listener functions if they employ a SimpleBlitButton. You
score, time remaining, and other useful information can will see this when we examine the GameFrameWork class
be displayed to the user with a very basic look and feel file. It can also be used for any game or application that
by using this class. It can be used as is, but when you needs to send a basic integer id along with an Event
start to make your own commercial games, you might instance.
find it useful to extend this class with more functionality.
This very basic class is used inside the framework to The CustomEventLevelScreenUpdate.as class
demonstrate how to use events from a Game instance This custom event will be used by the Game.as class
to update a game score board. instance to send data to a BasicScreen instance we will
The SideBySideScoreElement helper class is used to create called levelInScreen. The levelInScreen will have
display a text label and corresponding dynamic text the ability to display custom text between each level.
field as a pair side by side on the screen. For example, The event listnener for this event will change this text
it can be implemented by the ScoreBoard class to display with a value passed when the event is fired off. The
the word Score followed by the user’s current score. Main.as (GameFrameWork.as sub-class) will listen for this
event and pass the data to the levelInScreen.
The Game class
The Game class is a stub style class that all games The CustomEventScoreBoardUpdate.as class
in the framework will inherit from. It contains the This custom event will be used by the the Game.as class
basic variables and functions needed to work with the instance to update the values on the ScoreBoard class
GameFrameWork class. instance. The Main.as class will listen to for this event and
pass the data on to the ScoreBoard.as class instance.
The Custom event classes
The framework makes use of events to communicate The framework package structure
between classes. The instances of the Game class We will be organizing all of the code we will create into
will use events to communicate with the ScoreBoard a package structure. The reusable framework classes
and the Main classes. We will create a custom Main.as will be in one package, and the games we will create
class for each game. This Main class will be a sub- will be in a separate package. Let’s create these two
class (or child) of the GameFrameWork class. Some of the package structures now.
events we will use will be simple events. These are
instances of the standard Flash Event class used for The source folder
basic communication. By this, we mean events that Choose a spot on your disk drive of choice, and create
don’t need to send any data along with them. For a folder called source. This will be the root or base level
example, instances of the Game.as framework class will for all of the code and games we will create in this
have a constant variable called GAME_OVER. This constant book.
will be used as the name of a simple Event instance
that is fired off with the standard dispatchEvent function The classes package
call. This example GAME_OVER event wil be used to tell the The reusable framework classes will be in a package
Main.as to move to the game over (STATE_SYSTEM_GAME_OVER) called classes. Create a folder called classes inside the
state in the main state loop when the current game has source folder from the previous step. You should now
completed. have a folder structure that looks a little like this:

03/2010 (11) 21
ACTIONSCRIPT DEVELOPMENT

[source] with an assortment of tools and code integrated


[classes] development environments (IDEs). We are going to
focus on two such tools in this book: the Flash IDE
Next, we will create the actual package that will contain (the one with the library, timelines, drawing tools,
all of the source code for the reusable framework and so on all combined into a single tool) and Flash
classes. We will name this package com.efg.framework. Develop (a very popular, free IDE made specifically
To create this, you must first create a folder inside the for ActionScript development). You can use any
classes folder called com, then a folder called efg inside tool with this book, but you will need to follow the
the com folder, and finally a framework folder inside the documentation specific to your own tool when setting
efg folder. By the way, the efg is an abbreviation for up projects.
the book title, Essential Flash Games. You should now You will need to pay careful attention to linking the
have a folder structure that looks like this: reusable code package structure to your games,
because linking may vary depending on the Flash code
[source] editor environment you are using. Linking the package
[classes] to a game is actually a very simple process, but it differs
[com] between the various code IDE versions. Jeff does most
[efg] of his Flash game development Flash Develop using
[framework] the free Flex SDK that Adobe provides. Steve, on the
other-hand, uses the Flash IDE almost exclusively. We
When we start to create all of the class files necessary have combined our efforts on all of the chapter games
for the framework, they will all go into the framework to bring you code that will work with both a Flex SDK
folder. You will see that when we create these classes, project and a Flash IDE project.
the package name will look like this: On that note, the next two folders you will create
inside the stubgame folder are called flashIDE and flexSDK.
package com.efg.framework { You don’t have to create both for any project. You just
need to create the one that works with the tools you
The projects package are going to use to create Flash games. Each is set up
The second package we will create is called the projects differently, so pay attention to the specifics of the one
package. You can start this right away by creating you will be using the most.
a folder inside the root source folder called projects. The You should now have a projects folder that looks like
projects folder is not going to be a straight package this:
structure like the classes folder. It is organized in
a manner to allow individual custom game development [projects]
using the framework. [stubgame]
Inside this projects folder, we are going to create [flashIDE]
a unique folder for each game in the book. The first [flexSDK]
game we are going to create is called stubgame. A stub
is usually a function or class that contains very little (if The Flash IDE package structure
any) usable code but is instead a simple placeholder. The Flash IDE package structure begins right inside
Our game will be slightly more than a placeholder but the flashIDE folder. The package name is very similar
not much more. It will be used to demonstrate the basic to the classes package you saw in the last section.
functionality of the framework. Go ahead and create The package structure will be com.efg.games.[game
a folder called stubgame in the projects folder. You should name]. For instance, with the stub game we are going
have a projects set of folders that look like this: to create in this chapter, the package name will be
com.efg.games.stubgame. Go ahead and create those
[source] folders now. You should have this package structure
[classes] when you are complete:
...
[projects] [projects]
[stubgame] [stubgame]
[flashIDE]
Next, we are going to create two folders, each to [com]
hold a different version of our game. Why are we [efg]
going to do this? This book is meant to support Flash [games]
game development with a variety of tools. There [stubgame]
are many popular methods to create Flash games [flexSDK]

22 03/2010 (11)
Creating an AS3 Game Framework

The Flex SDK package structure Creating


The Flex SDK package structure is very similar to the the stub game project in the Flash IDE
Flash IDE package structure with one small difference. Follow these steps to set up stub game using the Flash
Flash Develop and other Flex tools use a specific set IDE:
of folders for organizing their own project structures. To
accommodate these and still have a common package 1. Start up your version of Flash. I am using CS3,
structure for our games, we must add the Flash Develop but this will work exactly the same in CS4 and
created src folder to the flexSDK folder. You will not have CS5.
to create the src folder or the package structure by 2. Create a .fla file in the /source/projects/stubgame/
hand, as Flash Develop will create it automatically for flashIDE/ folder called stubgame.
you when you start a new project. In the section called 3. In the /source/projects/stubgame/flashIDE/ folder,
Setting up the game in Flash Develop, we will go into create the following package structure for your
the details. For now, here is the way the structure will game: /com/efg/games/stubgame/
be laid out (including the Flash Develop specific folders 4. Set the frame rate of the Flash movie to 30 FPS.
such as bin, obj, and lib. If you have used Flash Develop Set the width and height both to 400.
to create a Flex SDK project, you will recognize the 5. Set the document class to com.efg.games.stubgame.Main
following structure: 6. We have not yet created the Main.as class so you
will see a warning. We are going to create this later
[projects] in this chapter.
[stubgame] 7. Add the framework reusable class package to the
[flexSDK] class path for the .fla file
[bin] • In the publish settings, select [Flash]>
[obj] [ActionScript 3 Setting].
[lib] • Click the Browse to Path button and find the /
[src] source folder we created earlier for the package
[com] structure. Select the classes folder, and click
[efg] the choose button. Now the com.efg.framework
[games] package will be available for use when we begin
[stubgame] to create our game. We have not created the
framework class files yet, but we will be doing
Notice that we have created the exact same package this very shortly.
structure inside the src folder as we will use with the
Flash IDE. The package name for our game will be Creating the stub game project in Flash Develop
com.efg.games.stubgame. And these are the steps to create the same project
The package name in the code for classes in both the using Flash Develop:
Flash IDE and Flex SDK will be the same:
1. Create a folder inside the [source][projects]
package com.efg.games.stubgame [stubgame] folder called [flexSDK ] (if you have not
{ already done so).
2. Start Flash Develop, and create a new project:
The Main.as and StubGame.as files • Select Flex 3 Project.
When we start to add files to the subgame package we will • Give the project the name stubgame.
be creating two subclasses (or children) of framework • The location should be the /source/projects/
classes that will be unique to our game. The Main.as will stubgame/flexSDK folder.
be created as a subclass (or child) of GameFrameWork.as • The package should be com.efg.games.stubgame.
framework class. The StubGame.as class will be a subclass • Do not have Flash Develop create a project
(or child) of the Game.as framework class. folder automatically. Make sure the Create
Folder For Project box is unchecked.
Starting a project using the framework • Click the OK button to create the project.
packages 3. Add the class path to the framework to the project:
You have just seen the basic package structure for both • Go to the [project]>[properties]>[classpaths] menu
the framework reusable classes and the projects we are item.
going to create. Let’s make use of this right away by • Click the add class path button.
creating a project for the stub game. The stub game will • Find the /source folder we created earlier, and
be very similar to the Chapter 1 game where the player select the classes subfolder.
is tasked with clicking the mouse ten times. • Click the ok button and then the apply button.

03/2010 (11) 23
ACTIONSCRIPT DEVELOPMENT

You now have the basic structure to start creating State Machines
projects inside the framework. We are now going to A traditional state machine at its very basic is
discuss a few topics concerning the structure of the a mechanism that controls the state, or current actions
framework classes and then move into building the a system can perform. Sometimes this is called a finite
reusable framework code. state machine. Finite state machines have traditionally
been used to model complex mathematical computations
Here are a couple of things to note: and more recently artificial intelligence. The finite in the
For Flex Builder, Flash Builder, or other IDEs, please name refers to the fact that the system can only be in
refer to the documentation provided for that product a single state at any one time. Our game framework is
to create a new project and set the default compile built on a simple state machine pattern that employs
class. a separate code function or method for each state.
A common method of Flash development is to use There are many other styles of state machines; some
the Flash IDE for assets and organization and Flash use entire classes for each individual state (sometimes
Develop for code editing. If this is your workflow of called an object-oriented state machine) and some use
choice, you will want to follow the Flash IDE folder a simple switch:case statement block called on each
and package structure rather than the Flex SDK folder frame tick to control state. We will use a third type that
structure. borrows from these two.
We call our state machine pattern a function reference
Creating game timers pattern. Unlike the object-oriented state machine, our
There are two basic methods that most Flash developers machine will contain a separate method or function
implement when creating a frame-based game timer. for each state inside a single framework class. Each
By frame-based, we mean a timer that uses the idea of these state functions will control elements in the
of a segment of time broken up into logical slices (or framework such as instances of the BasicScreen and Game
frames) to manage game logic. There are other types classes. We will use a switch:case statement to move
of methods for timing game updates, but we will make between states. Unlike the afore mentioned very simple
extensive use of time-slice or frame-based timers in switch/case state machine structures that call this
this book. The basic game timer we will use most of switch/state control structure on each frame tick, we only
the games will attempt to squeeze all processing and need to call it when we are switching states. The switch:
screen updates into each segment or frame. We will case we call will simply change the function reference we
also explore a time-step timer and a sleep-based timer call on each frame tick. The GameFrameWork.as will contain
in chapter 11. the state machine that controls overall game flow. This
The first timer method is the Event.ENTER_FRAME event will move our game system between states defined in
timer. The standard Event.ENTER_FRAME event handler the FrameWorkStates.as file.
will attempt to run the game loop at the .swf file’s set Each individual game package we create will contain
frame rate. This very handy game loop timer has been a Main.as (in the game’s own package structure) that will
in use for a number of years. The second standard extend GameFrameWork.as. We will also create a unique
game loop timer method makes use of the Timer Game.as child class for each game. The Game class
class. The Timer class is used to call the game loop children that we create can also employ their own
at millisecond intervals specified by a delay interval. internal state machines based on the function reference
For example, if the millisecond delay interval is set to pattern when needed.
100, the Timer instance would run ten times a second
(there are 1,000 milliseconds in a single second). Richard (Squize) Myles of www.gamingyourway.com
Our framework will begin by using this Timer instance was one of the first to offer the idea of a function
game loop timer. We will do this so we can make use reference state machine for ActionScript 3 on his well-
of the TimerEvent.TIMER updateAfterEvent function. As respected blog.
you will see, this function will help smooth out screen
updates. The FrameWorkStates.as class file
This class file is a simple collection of constants that
Defining frame timer tick will define the states for the game framework. They
You will see the phrases frame timer tick, timer tick, and will be consumed by the GameFrameWork.as class file. The
frame tick used in this book. When we refer to a tick following code listing shows the entire code for this file;
or a frame tick, we simply mean one frame’s worth of you will want to create this file according to the package
processing. When we run a game at 30 frames per structure in the previous section: see (Listing 1).
second, we have 30 ticks or 30 frame ticks. This also The first thing you should notice about this class is
means that we only have 33.33 milliseconds (or 1,000/ the package name in the first line. It conforms to the
30) inside each tick to do all of our processing. file system structure we created earlier. No matter if

24 03/2010 (11)
Creating an AS3 Game Framework

you are using a version of Flash, Flex Builder, Flash • STATE _ SYSTEM _ NEW _ GAME : This state will call the
Builder, Flash Develop, TextMate, or even plain game logic class and fire off its game.newGame()
old Notepad, this package name will be the same. function. It does not wait but moves on to the NEW _
The package name is not depended on the code LEVEL state right away.
development environment but the chosen file structure • STATE _ SYSTEM _ NEW _ LEVEL : With this state, we can
for organizing the code. Save this file in the location call the game.newLevel() function to set up a new level
we created previously. for the given game.
• STATE _ SYSTEM _ LEVEL _ IN : This state is used to display
/source/classes/com/efg/framework/FrameWorkStates.as some basic information, if needed, for the beginning
of a level. In this basic game, we simply display the
The state variables level screen and wait a few seconds before moving
The state variables are constants that the game loop on. The wait is accomplished by changing state
state machine will use to move between game states. to the STATE _ SYSTEM _ WAIT state for the specified
We have set up the most common basic states in this number of frame ticks.
sample file, but you will be able to create as many as • STATE _ SYSTEM _ GAME _ PLAY: This one simply calls the
you need. As we progress through the chapters, more game logic class’s runGame function repeatedly and
will be added as necessary. lets the game take care of its own logic and states.
• STATE _ SYSTEM _ GAME _ OVER : The game over state
• STATE _ SYSTEM _ TITLE : This state is used to display displays the basic game over screen and waits for
a basic title screen with an OK button for the user the OK button to be clicked before moving back
to click to move on. Once the instructions are on to the instructions screen. It quickly changes state
the screen, the state will change to the next state. to the STATE _ SYSTEM _ WAIT _ FOR _ CLOSE until the OK
• STATE _ SYSTEM _ WAIT _ FOR _ CLOSE : This one waits until button is clicked.
the OK button is clicked for any instance of the • STATE _ SYSTEM _ WAIT: This state waits for a specified
BasicScreen class. number of frames and then fires off a simple
• STATE _ SYSTEM _ INSTRUCTIONS : This state is used to custom event constant called WAIT _ COMPLETE .
display basic instructions with the same OK button
as in the SYSTEM _ TITLE state. It also changes to the The GameFrameWork.as class file
STATE _ SYSTEM _ WAIT _ FOR _ CLOSE state until the OK The GameFrameWork.as will be that parent of our game’s
button is clicked. document class. Main.as (the game’s document class)
for our games will extend this class and call
Listing 1. functions to modify the framework for each unique
game. The entire code listing is provided at the
package com.efg.framework end of this section. We will explore it in detail once
{ your have had a chance to type in the code. The
/** location for this file in the package structure is
* ...
* @author Jeff and Steve Fulton /source/classes/com/efg/framework/GameFrameWork.as
*
*/ The GameFrameWork.as will be the parent class
public class FrameWorkStates { to the Main.as class we will use for our games,
public static const STATE_SYSTEM_WAIT_FOR_CLOSE:int = 0; and it’s shown in the following listing. In later
public static const STATE_SYSTEM_TITLE:int = 1; chapters, we will add some functions to this file
public static const STATE_SYSTEM_INSTRUCTIONS:int = 2; and even create one that uses a completely
public static const STATE_SYSTEM_NEW_GAME:int = 3; different timer. The Main.as will subclass this
public static const STATE_SYSTEM_GAME_OVER:int = 4; class with the extends syntax and override the
public static const STATE_SYSTEM_NEW_LEVEL:int = 5; blank stub init function we are about to create.
public static const STATE_SYSTEM_LEVEL_IN:int = 6; This class will also contain all of the state
public static const STATE_SYSTEM_GAME_PLAY:int = 7; functions that coincide with the state variables
public static const STATE_SYSTEM_LEVEL_OUT:int = 8; in the FrameWorkStates class. All of the functions
public static const STATE_SYSTEM_WAIT:int = 9; in the GameFrameWork.as are public so all can be
} overridden by the Main.as if needed. In this way,
we can customize the behavior of the state
} functions if we need to.
For example, in later chapters, we will want to play
music on the title screen. The function call to play

03/2010 (11) 25
ACTIONSCRIPT DEVELOPMENT

the music will need to be added to the systemTitle state The class imports
function. Not all games will need this though, so we will The class import section contains the necessary Flash
not add it to the GameFrameWork.as file’s systemTitleFunction. core classes needed for the Main class. Notice the
Instead, we will create a new version of the function package name coincides with the package structure we
in Main.as to override the one in GameFrameWork.as. The created earlier in the chapter for the framework:
new one will play the sound needed and then call the
systemTitle function inside GameFrameWork.as with the package com.efg.framework
super.systemTitle() function call see (Listing 2). {

Listing 2.

package com.efg.framework //waitTime is used in conjunction with the


{ //STATE_SYSTEM_WAIT state
import flash.display.Bitmap; // it suspends the game and allows animation or
import flash.display.BitmapData; other
import flash.display.MovieClip; //processing to finish
import flash.events.Event;
import flash.geom.Point; public var waitTime:int;
import flash.text.TextFormat; public var waitCount:int=0;
import flash.utils.Timer;
import flash.events.TimerEvent; public function GameFrameWork() {

public class GameFrameWork extends MovieClip { }

public static const EVENT_WAIT_COMPLETE:String = public function init():void {


"wait complete"; //stub to override
}
public var systemFunction:Function;
public var currentSystemState:int; public function setApplicationBackGround(width:
public var nextSystemState:int; Number,�
public var lastSystemState:int; height:Number,isTransparent:Boolean = false, �
color:uint = 0x000000):void {
public var appBackBitmapData:BitmapData;
public var appBackBitmap:Bitmap; ; appBackBitmapData = new BitmapData(width,
height, �
public var frameRate:int; isTransparent, color);
public var timerPeriod:Number;
public var gameTimer:Timer; appBackBitmap = new Bitmap(appBackBitmapData);
addChild(appBackBitmap);
public var titleScreen:BasicScreen; }
public var gameOverScreen:BasicScreen;
public var instructionsScreen:BasicScreen; public function startTimer():void {
public var levelInScreen:BasicScreen; timerPeriod = 1000 / frameRate;
public var screenTextFormat:TextFormat; gameTimer=new Timer(timerPeriod);
public var screenButtonFormat:TextFormat; gameTimer.addEventListener(TimerEvent.TIMER,
runGame);
public var levelInText:String; gameTimer.start();
}
public var scoreBoard:ScoreBoard;
public var scoreBoardTextFormat:TextFormat; public function runGame(e:TimerEvent):void {
systemFunction();
//Game is our custom class to hold all logic for e.updateAfterEvent();
the game. }
public var game:Game;
//switchSystem state is called only when the

26 03/2010 (11)
Creating an AS3 Game Framework

Listing 2.
//state is to be changed
//(not every frame like in some switch/case Id.BUTTON_ID,�
//based simple state machines okButtonClickListener, false, 0, true);

public function switchSystemState(stateval:int): switchSystemState(FrameWorkStates.�


void { STATE_SYSTEM_WAIT_FOR_CLOSE);
lastSystemState = currentSystemState; nextSystemState = FrameWorkStates.STATE_
currentSystemState = stateval; SYSTEM_INSTRUCTIONS;
}
switch(stateval) {
case FrameWorkStates.STATE_SYSTEM_WAIT: public function systemInstructions():void {
systemFunction = systemWait;
break; addChild(instructionsScreen);

case FrameWorkStates.STATE_SYSTEM_WAIT_FOR_ instructionsScreen.addEventListener(CustomEven


CLOSE: tButtonId.�
systemFunction = systemWaitForClose; BUTTON_ID,okButtonClickListener, false, 0,
break; true);

case FrameWorkStates.STATE_SYSTEM_TITLE: switchSystemState(FrameWorkStates.�


systemFunction = systemTitle; STATE_SYSTEM_WAIT_FOR_CLOSE);
break;
nextSystemState = FrameWorkStates.STATE_
case FrameWorkStates.STATE_SYSTEM_ SYSTEM_NEW_GAME;
INSTRUCTIONS: }
systemFunction = systemInstructions;
break; public function systemNewGame():void {
addChild(game);
case FrameWorkStates.STATE_SYSTEM_NEW_GAME:
systemFunction = systemNewGame; game.addEventListener(CustomEventScoreBoardUp
break; date.�
UPDATE_TEXT,scoreBoardUpdateListener,false, 0,
case FrameWorkStates.STATE_SYSTEM_NEW_LEVEL: true);
systemFunction = systemNewLevel;
break; game.addEventListener(CustomEventLevelScreenU
pdate.�
case FrameWorkStates.STATE_SYSTEM_LEVEL_IN: UPDATE_TEXT,levelScreenUpdateListener,false,
systemFunction = systemLevelIn; 0, true);
break;
game.addEventListener(Game.GAME_OVER,
case FrameWorkStates.STATE_SYSTEM_GAME_PLAY: gameOverListener,�
systemFunction = systemGamePlay; false, 0, true);
break
game.addEventListener(Game.NEW_LEVEL,
case FrameWorkStates.STATE_SYSTEM_GAME_OVER: newLevelListener,�
systemFunction = systemGameOver; false, 0, true);
break;
} game.newGame();
} switchSystemState(FrameWorkStates.STATE_
SYSTEM_NEW_LEVEL);
public function systemTitle():void { }
addChild(titleScreen);
titleScreen.addEventListener(CustomEventButton public function systemNewLevel():void {

03/2010 (11) 27
ACTIONSCRIPT DEVELOPMENT

Listing 2.
game.newLevel();
switchSystemState(FrameWorkStates.STATE_ titleScreen.removeEventListener(CustomEv
SYSTEM_LEVEL_IN); entButtonId.�
} BUTTON_ID,okButtonClickListener);
break;
public function systemLevelIn():void {
addChild(levelInScreen); case FrameWorkStates.STATE_SYSTEM_
waitTime = 30; INSTRUCTIONS:
switchSystemState(FrameWorkStates.STATE_ removeChild(instructionsScreen);
SYSTEM_WAIT);
nextSystemState = FrameWorkStates.STATE_ instructionsScreen.removeEventListener(�
SYSTEM_GAME_PLAY; CustomEventButtonId.BUTTON_ID,okButtonC
addEventListener(EVENT_WAIT_COMPLETE, � lickListener);
waitCompleteListener, false, 0, true); break;
}
case FrameWorkStates.STATE_SYSTEM_GAME_OVER:
public function systemGameOver():void { removeChild(gameOverScreen);
removeChild(game);
addChild(gameOverScreen); gameOverScreen.removeEventListener(�
gameOverScreen.addEventListener(CustomEventBu CustomEventButtonId.BUTTON_ID,okButtonC
ttonId.� lickListener);
BUTTON_ID,okButtonClickListener, false, 0, break;
true); }
switchSystemState(nextSystemState);
switchSystemState(FrameWorkStates.� }
STATE_SYSTEM_WAIT_FOR_CLOSE);
public function scoreBoardUpdateListener(e:�
nextSystemState = FrameWorkStates.STATE_ CustomEventScoreBoardUpdate):void {
SYSTEM_TITLE;
} scoreBoard.update(e.element, e.value);
}

public function systemGamePlay():void { public function levelScreenUpdateListener(e:�


game.runGame(); CustomEventLevelScreenUpdate):void {
} levelInScreen.setDisplayText(levelInText +
e.text);
public function systemWaitForClose():void { }
//do nothing
} //gameOverListener listens for Game.GAMEOVER
simple
public function systemWait():void { //custom events calls and changes state
waitCount++; accordingly
if (waitCount > waitTime) {
waitCount = 0; public function gameOverListener(e:Event):void {
dispatchEvent(new Event(EVENT_WAIT_COMPLETE)); switchSystemState(FrameWorkStates.STATE_
} SYSTEM_GAME_OVER);
}
game.removeEventListener(CustomEventScoreBoard
public function okButtonClickListener(e: Update.�
CustomEventButtonId):void { UPDATE_TEXT,scoreBoardUpdateListener);
switch(e.id) {
case FrameWorkStates.STATE_SYSTEM_TITLE: game.removeEventListener(CustomEventLevelScree
removeChild(titleScreen); nUpdate.�

28 03/2010 (11)
Creating an AS3 Game Framework

integer variables to hold the value of the current state


Listing 2.
(currentSystemState), the last state (lastSystemState)
and the next state (nextSystemState) for processing
UPDATE_TEXT, levelScreenUpdateListener); purposes. These states should not be confused with
an actual game pause function. This will be handled
game.removeEventListener(Game.GAME_OVER, in a different manner and added to the framework in
gameOverListener); Chapter 11.
game.removeEventListener(Game.NEW_LEVEL,
newLevelListener); If you are using the Flash IDE and have any assets in
} the library that need to be exported in the first frame,
you must extend MovieClip and not Sprite even if you
//newLevelListener listens for Game.NEWLEVEL don’t plan to use the main time line for anything else.
//simple custom events calls and changes We have extended MovieClip for the GameFrameWork so it
state accordingly will work with both Flex SDK and Flash IDE projects.

public function newLevelListener(e:Event):void { The state control variables


switchSystemState(FrameWorkStates.STATE_ The control variables keep the system functioning
SYSTEM_NEW_LEVEL); within the context of the current state. The main control
} variable is an instance of the Function class called
systemFunction. This function holds a reference to the
public function waitCompleteListener(e:Event): current function that will be repeatedly called on each
void { frame tick. This saves us from having to evaluate
switch(lastSystemState) { a switch:case statement on each frame to decide which
case FrameWorkStates.STATE_SYSTEM_LEVEL_ function to call. The function is changed to a new
IN: reference by called the switchSystemState() function and
removeChild(levelInScreen); passing a new constant that represents the new state.
break
} Optimization! switchSystemState() is the first of many
removeEventListener(EVENT_WAIT_COMPLETE,wai optimizations we will make to the game framework.
tCompleteListener); All of these optimizations will make the Flash games
switchSystemState(nextSystemState); run much more efficiently. These efficiencies in the
} game framework will allow the actual game code to
} perform more complex operations and still run with
} a reasonable frame rate.

We also must import all of the classes needed for the The currentSystemState integer variable holds a number
framework to run. You will see this put to use shortly. representing the constant of the current state the
system is running. The nextSystemState contains the
The variable definitions constant integer value for the state to transition
The variable definition section defines all of the global to after this state is complete. The lastSystemState
scope variables for the class. These include all of the variable holds the integer constant of the previous
variables needed for the state machine, screens, and system state. This is used in the rare occurrence that
the game timer. the game loop needs to return to the previous system
We will make use of constants to define the current state.
state and a set of variables to hold the state information. The lastSystemState variable will become useful
These have been be defined on the FrameWorkStates.as when we use a shared state such as STATE_SYSTEM_WAIT.
file we created in the last section. More states can be The STATE_SYSTEM_LEVEL_IN state will implement a 30-
added to the basic ones, but these will be sufficient millisecond delay before moving on to the STATE_SYSTEM_
for many games that we will create in this book. There GAME_PLAY state. The nextSystemState will be STATE_SYSTEM_
are two special states that are used for the system WAIT and the lastSystemState will be STATE_SYSTEM_LEVEL_IN.
and wait for button clicks or things like animations to When the 30-millisecond wait time has expired, the
complete. These are the STATE_SYSTEM_WAIT_FOR_CLOSE waitCompleteListener function will be called. It will use the
and STATE_SYSTEM_WAIT respectively. We will also make lastSystemState to determine where the processing was
use of a generic function called systemFunction before the wait was started. You’ll see this in detail later
that will hold the current state function to call in our in this chapter when we examine the waitCompleteListener
game loop. Combined with this, we use a set of function.

03/2010 (11) 29
ACTIONSCRIPT DEVELOPMENT

The background fill variables attempt because if the game includes too many on
All Flash applications have a background color of screen moving objects or more logic than can be
some type. No matter what game we are going to be computed inside the timerPeriod number of milliseconds
creating, the framework can control this background (or a combination of both), then there will be a noticable
color. You should never rely on the background slowdown in the game screen updates. In later
color setting in HTML for your Flash application’s chapters, we will add functionality to the runGame function
background color. This leaves the HTML embed code to mitigate some of these issues.
with control over major aspect of your application.
If you are creating a viral game to be placed on The screen definition variables
game portals, you will lose control of your game’s The screen definition variables create instances of
background color, and it will default to what ever the our BasicScreen class. This is a rather simple class that
game portal operators have selected as the standard allows a single positional text box and an OK button
background color in their embed code. The framework on the screen. We will use this simple screen for the
allows you to override the HTML settings here by title, instructions, level, and game over screens. We
placing a simple colored Bitmap behind the entire will customize each screen when we create the init
application. We will simply define a BitmapData object function override in our game’s Main.as class. Note that
called appBackBitmapData and a Bitmap object called the levelInText is a special variable. Setting this string
appBackBitmap that will be used to place the BitmapData to a default value will allow the leveInScreen to display
onto the displayList. some default text along on each new level. This text
We will not define the background in the can be combined with dynamic text to create a screen
GameFrameWork.as file, but rather the Main.as subclass of that says something like Level 1 with the word Level
the GameFrameWork will set the background if needed in its being the default text and the number 1 being the
init function override. dynamic text.

The timer variables public var titleScreen:BasicScreen;


The timer will control the frame rate of the game and public var gameOverScreen:BasicScreen;
help smooth out the display by employing the Timer public var instructionsScreen:BasicScreen;
Event.updateAfterEvent method. The frameRate variable public var levelInScreen:BasicScreen;
will be defined in Main.as as the number of frame public var levelInText:String;
ticks per second we want our game timer to run. public var screenTextFormat:TextFormat;
The most important thing to note is that we are public var screenButtonFormat:TextFormat;
making use of the built-in Timer class (gameTimer). We
are not using the standard EnterFrame event. This allows We also create two TextFormat objects that will be used
us to create our own frame rate for the game and for defining the format of the text on the screens and
specify it in the frameRate variable. By doing this, we the format of the button text.
can control game timer tick rate independent of the .swf
file’s frame rate (FPS). The .swf file can have a frame The ScoreBoard variables
rate setting of 25 (for example), but the game can run The scoreBoard instance of the ScoreBoard class will
at a 30 frame ticks a second. To do this, we first set handle a simple heads up display (HUD) for the
the frameRate to the desired number of frame update user with information such as the current score. It
ticks we want per second (30). When Main.as calls the is a simple framework class that will be customized
startTimer function (described in detail when we get to in the init function override in each game’s Main.as
the section on the init function), the gameTimer is put into class. The changes will depend on the game that
action. First, we will calculate the timerPeriod value as is to be created. We also define a TextFormatObject
1000/frameRate. With the updateAfterEvent function call (in for the basic look of the text for our scoreboard text:
the runGame function), we help to smooth out the render scoreBoardTextFormat.
of the screen by asking the Flash display engine to
update at the rate of the Timer, not the frame rate set
in the .swf. So, going back to our example, if the game
SWF is set to run at 25 FPS, and the frameRate is set The next part of the article in the June issue of FFD
to 30 ticks, the updateAfterEvent will help to smooth out Magazine
the rendering of the screen by asking the Flash display
engine to update at the timer tick rate (30), not the .swf
file’s FPS setting (25). JEFF FULTON
The timerPeriod will be passed into the Timer instance
and the game will attempt to run at this rate. We say STEVE FULTON

30 03/2010 (11)
ACTIONSCRIPT DEVELOPMENT

Creating an XML Photo Gallery


with AS3

Searching the Internet you’ll find dozens, if not hundreds of


examples of photo galleries created with Flash.

What you will learn… What you should know…


• How to create an ActionScript application in Flex Builder 3 • Familiar with general programming concepts such as data ty-
• How to use ActionScript to parse an XML �le pes, variables, loops, and functions
• Familiar with class creation and construction
• Some understanding of XML

O
n my quest of learning Flash, I often became notice. Without having to open up Flash. Now, what
frustrated of how difficult it was to update the could be better than that.
contents of my application. Meaning, if I wanted In this article, you’re going to learn how to create a new
to change out an image or piece of copy, I had to open ActionScript project in Flex Builder 3, and write ActionScript
up Flash, go to my library, find the Movie Clip that had 3.0 code that will load in an XML file, display the images,
my asset in it, and republish. I thought to myself, this is on screen, and add some interactivity to the scene.
no way to work, this is so inefficient. Enter XML in all
its glory. Constructing an application with enabled me Setting up Flex
to quickly and easily update my project at a moments Open up Flex and go to File> New>ActionScript Project.
A dialog window will open. In the project name field type
in PhotoGallery. Leave the use default location box
checked and click finish (see Figure 1).

Figure 1. New ActionScript window dialog Figure 2. ActionScript Compiler dialog

32 03/2010 (11)
Once you click finish, your project should open and
you should see PhotoGallery.as on screen. There are
a few steps that I like to take next that I do for every
project.
First, right click PhotoGallery folder in the Flex
Navigator window, click properties at the bottom, and
then click on the ActionScript Compiler link on the left
hand side. At the bottom you’ll see a check box that
is already selected to generate a HTML wrapper file.
Uncheck that and click ok. A warning message will
appear saying that the html-template folder will be
deleted. Don’t worry about that because we haven’t
put anything in that folder. Click ok. I personally don’t
like to have a browser window open every time I run
my application (see Figure 2).
Secondly, we’ll be using a tweening library called
Tweener. In order to use Tweener we have to first
download it (http://code.google.com/p/tweener/). Be
sure to download the ActionScript 3.0 version and create
a folder on your desktop or any other place and name
it code. Place the contents of that download into that
folder. Next, go back to Flex and again right click the
PhotoGallery folder and click properties again, and this
time you’ll click the ActionScript Build Path link. This
window gives us the ability to add assets to our project,
so we can use them in our project. Click the Add Folder
button, browser to the code folder you just created, click
ok, and click ok again to close the window. Now that
folder and all its contents will be included in our project
(see Figure 3).
Next, right click the src folder in your project, scroll
over to new and add a new folder. Name this folder
classes. This folder will contain two classes that we’ll be
using. Then repeat the same steps but this time name
the folder images. This folder will contain all the images

Figure 3. ActionScript Build Path dialog

03/2010 (11) 33
ACTIONSCRIPT DEVELOPMENT

Listing 1. gallery.xml

<?xml version="1.0" encoding="UTF-8"?> <description>This is a description for the ninth


<gallery image_height="150" image_width="150" image_ image</description>
gap="5" rows="3"> <thumb_path>images/thumb.jpg</thumb_path>
<photo> <full_path>images/full.gif</full_path>
<description>This is a description for the first </photo>
image</description> <photo>
<thumb_path>images/thumb.jpg</thumb_path> <description>This is a description for the tenth
<full_path>images/full.gif</full_path> image</description>
</photo> <thumb_path>images/thumb.jpg</thumb_path>
<photo> <full_path>images/full.gif</full_path>
<description>This is a description for the second </photo>
image</description> <photo>
<thumb_path>images/thumb.jpg</thumb_path> <description>This is a description for the
<full_path>images/full.gif</full_path> eleventh image</description>
</photo> <thumb_path>images/thumb.jpg</thumb_path>
<photo> <full_path>images/full.gif</full_path>
<description>This is a description for the third </photo>
image</description> <photo>
<thumb_path>images/thumb.jpg</thumb_path> <description>This is a description for the twelfth
<full_path>images/full.gif</full_path> image</description>
</photo> <thumb_path>images/thumb.jpg</thumb_path>
<photo> <full_path>images/full.gif</full_path>
<description>This is a description for the fourth </photo>
image</description> <photo>
<thumb_path>images/thumb.jpg</thumb_path> <description>This is a description for the
<full_path>images/full.gif</full_path> thirteenth image</description>
</photo> <thumb_path>images/thumb.jpg</thumb_path>
<photo> <full_path>images/full.gif</full_path>
<description>This is a description for the fifth </photo>
image</description> <photo>
<thumb_path>images/thumb.jpg</thumb_path> <description>This is a description for the
<full_path>images/full.gif</full_path> fourteenth image</description>
</photo> <thumb_path>images/thumb.jpg</thumb_path>
<photo> <full_path>images/full.gif</full_path>
<description>This is a description for the sixth </photo>
image</description> <photo>
<thumb_path>images/thumb.jpg</thumb_path> <description>This is a description for the
<full_path>images/full.gif</full_path> fifteenth image</description>
</photo> <thumb_path>images/thumb.jpg</thumb_path>
<photo> <full_path>images/full.gif</full_path>
<description>This is a description for the seventh </photo>
image</description> </gallery>
<thumb_path>images/thumb.jpg</thumb_path>
<full_path>images/full.gif</full_path>
</photo>
<photo>
<description>This is a description for the eighth
image</description>
<thumb_path>images/thumb.jpg</thumb_path>
<full_path>images/full.gif</full_path>
</photo>
<photo>

34 03/2010 (11)
ACTIONSCRIPT DEVELOPMENT

Listing 2. PhotoGallery.as

package { private function init ():void


// Imports {
import caurina.transitions.Tweener; _xmlLoader = new URLLoader ();
_xmlLoader.addEventListener (Event.COMPLETE,
import classes.BigPhoto; xmlComplete, false, 0, true);
import classes.ThumbNail; _xmlLoader.load (new URLRequest
("gallery.xml"));
import flash.display.Bitmap; }
import flash.display.Sprite;
import flash.events.Event; // XML Complete
import flash.events.MouseEvent; private function xmlComplete (e:Event):void
import flash.net.URLLoader; {
import flash.net.URLRequest; // Store the XML data
_xml = new XML (e.target.data);
[SWF(width="466", height="515", backgroundColor="#00
0000", frameRate="30")] loadImages ();
public class PhotoGallery extends Sprite
{ // Clean up
// Containers _xmlLoader.removeEventListener
private var _thumbContainer:Sprite; // Stores (Event.COMPLETE, xmlComplete);
the thumbnails _xmlLoader = null;
private var _nextButton:Sprite; // Stores }
the next arrow
private var _backButton:Sprite; // Stores // Load in the thumbs
the back arrow private function loadImages ():void
private var _bigPhoto:BigPhoto; // {
Container for the big image // Temporary variables
var imageHeight:uint = _xml.@image_height;
// XML var imageWidth:uint = _xml.@image_width;
private var _xmlLoader:URLLoader; var imageGap:uint = _xml.@image_gap;
// Loads the XML file var rows:uint = _xml.@rows;
private var _xml:XML; // var rowCounter:uint = 0;
Stores the XML data var columnCounter:uint = 0;

// Image Assets // Instantiate the container and position it


[Embed(source="assets/next-arrow.png")] on screen
private var _nextArrow:Class; _thumbContainer = new Sprite ();
// Embedded asset for the next _thumbContainer.x = 78;
arrow _thumbContainer.y = 78;
_thumbContainer.buttonMode = true;
[Embed(source="assets/back-arrow.png")] _thumbContainer.addEventListener
private var _backArrow:Class; (MouseEvent.CLICK, thumbClick,
// Embedded asset for the back false, 0, true);
arrow this.addChild (_thumbContainer);

// Constructor // Loop through the images and create the


public function PhotoGallery() visual grid
{ for (var i:uint = 0; i < _xml.photo.length ();
init (); i++)
} {
var path:String = _xml.photo[i].thumb_path;
// Initializing method var description:String = _xml.photo[i].desc

36 03/2010 (11)
Creating an XML Photo Gallery with AS3

Listing 2. PhotoGallery.as

ription; disableNavigation ();


Tweener.addTween (_thumbContainer, {x:
// Create the thumbnail _thumbContainer.x + 155, time:
var p:ThumbNail = new ThumbNail (); 0.75, transition:"easeOutExpo",
p.newID = i; onComplete:enableNavigation});
p.loadImage (path); }
p.description = description; }
p.x = (imageWidth + imageGap) *
columnCounter; // This method handles the click event for the
p.y = (imageHeight + imageGap) * thumbnails
rowCounter; private function thumbClick (e:MouseEvent):void
_thumbContainer.addChild (p); {
disableNavigation ();
// Create the grid
if ((rowCounter + 1) < rows) // Disable the container that stores the
{ thumbnails
rowCounter++; _thumbContainer.buttonMode = false;
} _thumbContainer.mouseChildren = false;
else _thumbContainer.removeEventListener
{ (MouseEvent.CLICK, thumbClick);
rowCounter = 0;
columnCounter++; // Get the full image path
} var imagePath:String = _xml.photo[e.target.newI
} D].full_path;

// Setup the navigation // Instantiate the big photo


createNavigation (); _bigPhoto = new BigPhoto ();
} _bigPhoto.buttonMode = true;
_bigPhoto.x = 108;
// This method handles the click event for the _bigPhoto.y = 107.5;
next arrow _bigPhoto.alpha = 0;
private function nextClick (e:MouseEvent):void _bigPhoto.loadImage (imagePath);
{ _bigPhoto.addEventListener (MouseEvent.CLICK,
// 155 is the width + spacing closePhoto, false, 0, true);
if (-_thumbContainer.x < (_thumbContainer.width this.addChild (_bigPhoto);
– stage.stageWidth – 155))
{ // Fade up the photo
disableNavigation (); Tweener.addTween (_bigPhoto, {alpha:1, time:
Tweener.addTween (_thumbContainer, {x: 1});
_thumbContainer.x – 155, time: }
0.75, transition:"easeOutExpo",
onComplete:enableNavigation}); // Fade out the photo
// When the image finishes fading, delete the
} photo, and enable the navigation
} items
private function closePhoto (e:MouseEvent):void
// This method handles the click event for the {
back arrow Tweener.addTween (_bigPhoto, {alpha:0, time:1,
private function previousClick (e:MouseEvent):void onComplete:deletePhoto});
{ }
if (-_thumbContainer.x > 0)
{ private function deletePhoto ():void

03/2010 (11) 37
ACTIONSCRIPT DEVELOPMENT

Listing 2. PhotoGallery.as

{ _nextButton.addEventListener
_bigPhoto.buttonMode = false; (MouseEvent.CLICK, nextClick, false,
_bigPhoto.removeEventListener 0, true);
(MouseEvent.CLICK, closePhoto);
_bigPhoto.destroy (); _backButton.buttonMode = true;
_backButton.addEventListener
this.removeChild (_bigPhoto); (MouseEvent.CLICK, previousClick,
_bigPhoto = null; false, 0, true);
}
_thumbContainer.buttonMode = true;
_thumbContainer.mouseChildren = true; private function disableNavigation ():void
_thumbContainer.addEventListener {
(MouseEvent.CLICK, thumbClick, _nextButton.buttonMode = false;
false, 0, true); _nextButton.removeEventListener
(MouseEvent.CLICK, nextClick);
enableNavigation ();
} _backButton.buttonMode = false;
_backButton.removeEventListener
private function createNavigation ():void (MouseEvent.CLICK, previousClick);
{ }
// Instantiate the next arrow }
var n:Bitmap = new _nextArrow (); }

// Instantiate the nextButton container


// Add the next button as a child of the
nextButton container
_nextButton = new Sprite ();
this.addChild (_nextButton);
_nextButton.addChild (n);
_nextButton.x = stage.stageWidth – _
nextButton.width;
_nextButton.y = 475;

// Instantiate the back arrow


var b:Bitmap = new _backArrow ();

// Instantiate the backButton container


// Add the next button as a child of the
backButton container
_backButton = new Sprite ();
this.addChild (_backButton);
_backButton.addChild (b);
_backButton.x = _nextButton.x – _
nextButton.width – 5;
_backButton.y = 475;

enableNavigation ();
}

private function enableNavigation ():void


{
_nextButton.buttonMode = true;
Figure 4. New ActionScript class dialog

38 03/2010 (11)
Creating an XML Photo Gallery with AS3

Listing 3. ThumbNail.as

package classes // Instantiate the container


{ _imageContainer = new Sprite ();
import caurina.transitions.Tweener; _imageContainer.alpha = 0;
this.addChild (_imageContainer);
import flash.display.Loader;
import flash.display.Shape; createDescription ();
import flash.display.Sprite;
import flash.events.Event; this.mouseChildren = false;
import flash.events.MouseEvent; this.addEventListener (MouseEvent.MOUSE_OVER,
import flash.net.URLRequest; onMouseOver, false, 0, true);
import flash.text.TextField; this.addEventListener (MouseEvent.MOUSE_OUT,
import flash.text.TextFieldAutoSize; onMouseOut, false, 0, true);
import flash.text.TextFormat; }

public class ThumbNail extends Sprite /////////////////////////////////////////////////


{ //
// Containers // Public Methods
private var _imageLoader:Loader; // Loads in //
the thumbnail /////////////////////////////////////////////////
private var _imageContainer:Sprite; // public function loadImage (path:String):void
Container for the thumbnail {
private var _mask:Shape; // Container for the _imageLoader = new Loader ();
mask _imageLoader.contentLoaderInfo.addEventListen
private var _descriptionContainer:Sprite; // er (Event.COMPLETE, imageComplete,
Container for the description false, 0, true);
_imageLoader.load (new URLRequest (path));
// TextFields }
private var _description:TextField; //
TextField for the container // Getter/Setter Methods
public function get newID ():uint
// Logic {
private var _newID:uint; // The ID of the return this._newID;
object }

[Embed(systemFont="Arial", fontName="arial", public function set newID (value:uint):void


fontWeight="bold", {
mimeType='application/x-font- this._newID = value;
truetype')] }
private var _arial:Class; // Embedded asset
for the font public function get description ():String
{
// Constructor return this._description.text;
public function ThumbNail () }
{
super (); public function set description (value:String):void
{
init (); this._description.text = value;
} }

// Initializing method /////////////////////////////////////////////////


private function init ():void //
{ // Private Methods

03/2010 (11) 39
ACTIONSCRIPT DEVELOPMENT

Listing 3. ThumbNail.as

// private function createDescription ():void


///////////////////////////////////////////////// {
private function onMouseOver (e:MouseEvent):void // Instantiate the container
{ _descriptionContainer = new Sprite ();
Tweener.addTween (_descriptionContainer, _descriptionContainer.y = 150;
{y:75, time:0.5, transition: _descriptionContainer.graphics.beginFill
"easeOutExpo"}); (0x000000, 0.75);
} _descriptionContainer.graphics.drawRect (-75,
-75, 150, 75);
private function onMouseOut (e:MouseEvent):void _descriptionContainer.graphics.endFill ();
{ _imageContainer.addChild (_
Tweener.addTween (_descriptionContainer, descriptionContainer);
{y:150, time:0.5, transition:
"easeOutExpo"}); // Specify text formatting for the description
} Text Field
var tf:TextFormat = new TextFormat ();
private function imageComplete (e:Event):void tf.color = "0xFFFFFF";
{ tf.align = "center";
// Reposition the loaded content to the center tf.font = "arial";
_imageLoader.x = -(_imageLoader.width / 2); tf.bold = true;
_imageLoader.y = -(_imageLoader.height / 2); tf.size = 12;
_imageContainer.addChildAt (_imageLoader, 0);
// Instantiate the TextF ield
// Apply background after the image has _description = new TextField ();
completely loaded _description.x = -75;
drawBackground (); _description.y = -70;
_description.width = 150;
// Draw the mask around the description _description.wordWrap = true;
drawMask (); _description.embedFonts = true;
_description.defaultTextFormat = tf;
// Fade in the container _description.autoSize = TextFieldAutoSize.LEFT;
Tweener.addTween (_imageContainer, {alpha:1, _descriptionContainer.addChild (_description);
time:0.5}); }

// Clean up // Draws a mask our _descriptionContainer


_imageLoader.contentLoaderInfo.removeEv private function drawMask ():void
entListener (Event.COMPLETE, {
imageComplete); // Draw the mask shape
} _mask = new Shape ();
_mask.graphics.beginFill (0xFF0000);
// Draws a background behind _imageContainer _mask.graphics.drawRect (_imageLoader.x,
private function drawBackground ():void _imageLoader.y, _imageLoader.width,
{ _imageLoader.height);
_imageContainer.graphics.beginFill (0xFFFFFF); _mask.graphics.endFill ();
_imageContainer.graphics.drawRect (_ addChild (_mask);
imageLoader.x – 1, _imageLoader.y
– 1, _imageLoader.width + 2, // Apply the mask to the container
_imageLoader.height + 2); _descriptionContainer.mask = _mask;
_imageContainer.graphics.endFill (); }
} }
}
// Creates everything for the description

40 03/2010 (11)
Creating an XML Photo Gallery with AS3

Listing 4. BigPhoto.as

private function imageComplete (e:Event):void


package classes {
{ // Instantiate the container
import flash.display.Loader; _imageContainer = new Sprite ();
import flash.display.Sprite; this.addChild (_imageContainer);
import flash.events.Event;
import flash.net.URLRequest; // Add the loader
_imageContainer.addChild (_imageLoader);
public class BigPhoto extends Sprite
{ // Clean up
// Containers _imageLoader.contentLoaderInfo.removeEv
private var _imageLoader:Loader; // Loads in the entListener (Event.COMPLETE,
thumbnail imageComplete);
private var _imageContainer:Sprite; // Container }
for the thumbnail }
}
// Constructor
public function BigPhoto () that will be loaded into the application from XML. Finally,
{ create another folder and this time name it assets. This
super(); folder will contain the buttons that we’ll embed into our
} project.

///////////////////////////////////////////////// The Assets


// Before we start coding we need to create some visual
// Public Methods assets. Open up Photoshop or any other program
// you have for creating graphics and create an image
///////////////////////////////////////////////// that is 150x150 pixels. Fill it with a flat color and save
public function loadImage (path:String):void the image as thumb.jpg in the images folder you just
{ created. Next, create another image that’s 250x300
_imageLoader = new Loader (); pixels. Fill it with another color and save that image as
_imageLoader.contentLoaderInfo.addEventListen full.jpg into the same folder. These images will be used
er (Event.COMPLETE, imageComplete, for testing purposes only.
false, 0, true);
_imageLoader.load (new URLRequest (path));
}

// Clean up method
public function destroy ():void
{
_imageContainer.removeChild (_imageLoader);
_imageLoader.unload ();
_imageLoader = null;

this.removeChild (_imageContainer);
_imageContainer = null;
}

/////////////////////////////////////////////////
//
// Private Methods
//
/////////////////////////////////////////////////
Figure 5. Time to test!

03/2010 (11) 41
ACTIONSCRIPT DEVELOPMENT

We still have to create our navigation buttons that we’ll The Explanation
use to scroll through our gallery. Create two buttons that Our main focus is going to be what’s going on in
are 40x40 pixels and design them how you like. They PhotoGallery.as. This file contains the ActionScript that
should resemble forward and back buttons. Save the makes almost everything happen. We first start off by
forward arrow as next-arrow.png and the other as back- declaring our properties that will be used in the project.
arrow.png into the assets folder. Now that our assets You’ll notice a couple of embeded lines. These lines are
our created it’s time to code! MetaData tags that actually embed assets into the project.
The two embeded lines you see add the next-arrow.png
The XML file file and the back-arrow.png file. In the constructor, there is
Right click the src folder in the project, scroll over to one call to a method called init(). This method gets the
new, and click file. A dialog window will open and in the application going by requesting and loading in the XML
file name input box type gallery.xml (see Figure 4). Write File. When the file finishes loading, we store the XML
the code that you see from Listing 1 into gallery.xml. data into our _xml property. Next, we call the loadImages()
Line 1: is the XML declaration. This is needed to have method. This method is responsible for a big part of the
a well-formed XML document. application. We first gather some information from the
Line 2: declares the gallery root node. Notice in this XML file and store it in temporary variables:
node I’ve added attributes. Also, to have a well-formed
XML document, you must have one root node and all • imageWidth: stores the image _ height attributes value
attribute values must be in quotes. • imageWidth: stores the image _ width attributes value
Lines 3-7: declares a photo node with three children; • imageGap: stores the image _ gap attributes value
description, thumb_path, and full_path. description is • rows: stores the row attributes value
exactly as it sounds. It will contain a description for our • rowCounter: increments ever pass of the for loop. Is
thumbnail. thumb_path, contains the path to our thumbnail compared against the rows variable
image. Same goes for full_path, it contains the path to • columnCounter: increments once for every column
our full image. created.
I then just copy and pasted that and pasted it 14
times, just changing out the description. Remember The for loop cycles the XML file, creating a new ThumbNail
we’re just using dummy data. When you finish, go back object with every iteration. During each iteration, we
and add photos of your choice. create variables that store the path to the thumb nail
(path), and the description of the thumbnail (description).
The Classes We pass the variables into the methods of the ThumbNail
We’ll be using two additional classes for this project. class. Remember the ThumbNail class defines methods
One will be for the thumbnails and another for the full and properties that are specific to it. The class code is
image. Right click the classes folder, go to new, and click commented if you wish to explore it. Again, our main
ActionScript class. In the name field, type ThumbNail. For focus is PhotoGallery.as. To create the grid, we write if/
the Superclass, type in flash.display.Sprite. We’ll need else logic that compares the rowCounter variable to the
to extend from that class so we can use the functionality row variable. For every iteration of the loop, we increment
of that object but add our own (see Figure 4). that variable, if that variable becomes greater than rows,
Add another class, this time name it BigPhoto. It should we set it back to 0. rowCounter is then multiplied to the y-
also inherit from flash.display.Sprite. axis of each ThumbNail object. The rest of the code is
commented for you to explore.
Coding
Time to start writing the ActionScript for this project. Conclusion
Open up PhotoGallery.as from the Flex Navigator and You’ll notice I actually hard coded a lot of values directly
type in the code from Listing 2. Open up ThumbNail.as and in the ActionScript. Not too ideal. In the next part of this
type in the code from Listing 3. Open up BigPhoto.as tutorial, we’re going to come back to this code, and modify
and type in the code from Listing 4. Now that you have it to be a little more flexible and visually appealing. If you
all the code in, it’s time to test. In the menu bar, click have any questions, feel free to contact me through my
Run>Run PhotoGallery (see Figure 5) If you get an site (www.codedbyryan.com).
error, make sure you typed everything correctly. If all
went well, you should see the gallery open up. Click RYAN D’AGOSTINO
the buttons and watch the gallery scroll left and right. Ryan D’Agostino is an Interactive Developer at NAS Recruitment
Roll over the thumbnails to see the description scroll Communications in Cleveland, OH, part-time instructor at Virginia
up. Click on a thumbnail to see the full image fade in. Marti College of Art and Design in Lakewood, Ohio, and freelance
You might be wondering about what’s going on. I’ll try to designer and ActionScript developer. For more information about
break that down for you next. Ryan please visit http://www.codedbyryan.com/

42 03/2010 (11)
COMPONENTS

Custom Flash CS4


Components in Flash Builder 4

Flash Builder comes with a lot of components to cover


almost all of an apps needs. But what if you want
a custom look or functionality to a component. With Flash
Professional you can create custom components and import
them into Flash Builder for use in your application.

What you will learn… What you should know…


• How to create custom components in Flash Professional to im- • Flash Professional CS4
port into Flash Builder • Flash Builder 4
• Actionscript 3

C
omponents are the controls and containers Creating custom components takes two paths. The
that are the elements of the application that first is to create a skin for an existing Halo component
create the interface. They cover controls such in Flash, Illustrator, Photoshop or Fireworks or create
as buttons and check boxes, containers that can hold a custom skin for a Spark component using MXML.
other containers and controls, navigation elements and The second path is to create a completely custom
charts. Components can be added to your application in component using Flash Professional and importing it
variety of ways. They can be added through the design into the Flash Builder project. We are going to focus on
view, writing then in MXML or through ActionScript. the second path and create a custom component with
Flash Builder now has two major sets of Flash Professional.
components, the Halo set, which has been available The first step in creating a custom component
in previous versions of Flex, and the new Spark set. is to instal the Flex Component Kit mxp into Flash
The components from the Spark set have a direct Professional. This is an extension that will expose some
correlation to a component in the Halo set but not
all Halo components have been upgraded to the
Spark framework yet. The namespaces for these
components are added automatically when a MXML
document is created and you will notice there are now
multiple namespace in the main MXML document
already.

Figure 1. The component artwork Figure 2. Converting the movie clip

44 03/2010 (11)
COMPONENTS

Listing 1. The component class

package com.test
{
import mx.flash.UIMovieClip;
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.events.MouseEvent;
import flash.filters.GlowFilter;

public class SliderButton extends UIMovieClip


{

public static const BUTTON_CLICK:String = 'button click';


private var glow:GlowFilter = new GlowFilter(0x0000cc,.5,4,4,2,1,false,false);

public function SliderButton()


{
plusButton.buttonMode = true;
minusButton.buttonMode = true;

plusButton.addEventListener(MouseEvent.MOUSE_OVER, handleMouseOver);
plusButton.addEventListener(MouseEvent.MOUSE_OUT, handleMouseOut);
plusButton.addEventListener(MouseEvent.CLICK, handleMousePress);

minusButton.addEventListener(MouseEvent.MOUSE_OVER, handleMouseOver);
minusButton.addEventListener(MouseEvent.MOUSE_OUT, handleMouseOut);
minusButton.addEventListener(MouseEvent.CLICK, handleMousePress);
}
private function handleMouseOver(e:MouseEvent):void
{
e.currentTarget.filters = [glow];
}
private function handleMouseOut(e:MouseEvent):void
{
e.currentTarget.filters = [];
}
private function handleMousePress(e:MouseEvent):void
{
if(e.currentTarget.name == 'plusButton' && trackThumb.x < 134)
{
trackThumb.x++;
}
else if(e.currentTarget.name == 'minusButton' && trackThumb.x > 37)
{
trackThumb.x--;
}
dispatchEvent(new Event(SliderButton.BUTTON_CLICK));
}
}
}

46 03/2010 (11)
COMPONENTS

Figure 3. Setting the class of the movie clip


Figure 5. Creating the Flash Builder project
of the Flex classes to Flash allowing the component
to communicate with the application. Download the versions as far back as Flash 8, but I highly recommend
extension from the Adobe site at http://www.adobe.com/ using at least Flash 9 (CS 3).
cfusion/exchange/index.cfm?event=extensionDetail& Once the extension is installed, launch Flash
extid=1273018 and install using the Adobe Extension Professional and create a new ActionScript 3 project.
Manager. The extension should work with Flash We are going to create a simple slider button that has
a plus and minus button on each end of the button and
a track between them. When the plus and minus buttons
are clicked, the the track thumb will move one pixel in
either direction. There will also be a roll over behavior on
the buttons to change their look as the mouse rolls over
and off the buttons. Finally, Flash Builder will receive
the event of the button being pushed and update a text
input on the stage.
It is common to encapsulate the behaviors of the
component within itself and have events broadcast to
the containing application. If you think about some of
standard components in both Flash Builder and Flash
Professional and deconstruct them in your mind, you
will see that the same methods are used on them. The
NumericStepper is a lot like our component. It has
two buttons with a text field that displays a value that
is incremented or decremented with each push of the
button. The component itself does nothing to effect
the application until the code calls it to either send or
receive a value.
With our new document, we are going to create the
artwork for the component in the fla file. Create four
movie clips, one each for the scroll track, the plus button,
the minus button and the track thumb (Figure 1). The
naming and look of these movie clips are not important.
Once the movie clips are created and on the stage,
give each one an instance name. The names in the
Figure 4. Setting to export as SWC

48 03/2010 (11)
Custom Flash CS4 Components in Flash Builder 4

example files are: plusButton, minusButton and trackThumb.


The actual names do not matter and we don't need an Listing 2. The main MXML �le
instance name for the track since we are not going
to reference it in Flash Builder. Flash Builder will <?xml version="1.0" encoding="utf-8"?>
reference the instance names of the movie clips in the <s:Application xmlns:fx="http://ns.adobe.com/mxml/
components, we will use these later. 2009"
Now that the artwork has been created, it must be xmlns:s="library://ns.adobe.com/flex/
collected into its own movie clip. Select all of the artwork spark"
on the stage and choose Modify>>Convert to Symbol… xmlns:mx="library://ns.adobe.com/flex/
In the Library panel, there is a new symbol that is mx"
called in the sample files SliderButton. The name is width="200" height="110">
important here because this is how the Convert to Flex
Component mxp will name the class that Flash Builder <fx:Declarations>
will refer to later. <!-- Place non-visual elements (e.g.,
An external class will give the component the internal services, value objects) here
behaviors that were mentioned earlier as well as an -->
event to broadcast to the Flash Builder application </fx:Declarations>
(Listing 1). All the code in the class should be familiar, </s:Application>
but there are a few points to go over. First, the package
name is given the qualifier of com.test to identify that
the component belongs to our namespace. This is
not necessary but helpful when there are multiple extend the UIMovieClip class. This class, like the Flex
components or components from different publishers in Component in the library, exposes the behaviors and
the application. methods we set up in the class to the Flash Builder
The most important change is instead of having the application. In the import statements, use import
class extend the Sprite class, this class is going to mx.flash.UIMovieClip. The mx.flash class includes both
the UIMovieClip and ContainerMovieClip classes.
When the variables are declared, we set up a glow
filter that will be attached to the buttons when the
mouse rolls over them and a string constant for the
event we create later. In the constructor of the class,
the buttons receive the event listeners for the mouse
interactions and the handlers are added later in the
code. In the handleClick event handler, we use the event
dispatcher class to dispatch the event. Here we are just
dispatching a standard event with the constant that was
created earlier. You can just as easily dispatc a custom
event that has extra information attached to it.
Select the movie clip in the Library panel then select
Commands>>Convert Symbol to Flex Component
(Figure 2). The extension will do several operations
such as making the symbol available to ActionScript,
giving the symbol a class name, adding the Flex
Component to the library and others.
Save the file as SliderButton.as in the folder path
com/test/. When you declare the package name as
we have here, you must have the same hierarchy as
listed in the package name. Back in the fla, select the

Listing 3. The new component and name space

xmlns:test="com.test.*"
<test:SliderButton x="14" y="10" id="sliderButton"
/>

Figure 6. The Package Explorer

03/2010 (11) 49
COMPONENTS

SliderButton movie clip and select Properties… from server technologies. You can name the project anything
the contextual menu. Expand the advanced area if it you would like, in this case, I have name FB_Components
is not already and enter com.test.SliderButton in the and saved it in my default workspace.
Class: text field. Leave the Base Class: text field blank If you have not worked on a Flash Builder project yet,
and click OK (Figure 3). it is a lot like working on the Flex projects in the past
Select Publish Settings… from the file menu and click with some new MXML tags. You will also notice that the
on the Flash tab (Figure4). Under the SWF Settings Flex Navigator pane has now been replaced with the
area of the window, be sure that the Export SWC check Package Explorer (Figure 6).
box is checked. The swc is the part that Flash Builder The Package Explorer pane has a different
will use in the application. SWC are archives that organization than the Flex Navigator but the main
contain the classes and media assets of the component MXML file can still be found under src then under the
and make it easy to distribute the movie clip. default package.
Publish the SWF and SWC and we are ready to move Looking at the main MXML (Listing 2), you will see
to Flash Builder. that the three name spaces are added automatically
and the application begins with s:Application instead
Flash Builder of mx:Application. These are the minor differences to
In Flash Builder, create a new project. This example be on the look out for when working on a Flash Builder
we only need a basic Flash Builder project without any project.

Listing 4. The �nal MXML �le

<?xml version="1.0" encoding="utf-8"?>


<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="200" minHeight="110"
width="200" height="110"
initialize="init()"
xmlns:test="com.test.*">

<fx:Declarations>
<!-- Place non-visual elements (e.g., services, value objects) here -->
</fx:Declarations>

<fx:Script>
<![CDATA[

private function init():void


{
sliderButton.addEventListener(SliderButton.BUTTON_CLICK, updateText);
}

private function updateText(e:Event):void


{
pixelText.text = String(sliderButton.trackThumb.x);
}

]]>

</fx:Script>

<test:SliderButton x="14" y="10" id="sliderButton" />


<s:Label x="39" y="41" text="The position of the track thumb is:" textAlign="center" width="122"/>
<s:TextInput x="76" y="76" width="49" id="pixelText"/>
</s:Application>

50 03/2010 (11)
Custom Flash CS4 Components in Flash Builder 4

To get our component into the Flash Builder project,


we need to put the swc some where the project can On the 'Net
see it. On your desktop, navigate to where the swc was
• http://www.adobe.com
published to and copy the file. Then navigate to where • http://www.adobe.com/cfusion/exchange/index.cfm?even-
Flash Builder project is and put the swc into libs folder. t=extensionDetail&extid=1273018
I have found it is easier to keep the fla and swf files
out of the project then copy the swc over to the Flash
Builder project as needed. function every time the BUTTON_CLICK event is broadcast
Back in Flash Builder, open the libs folder under the from the SliderButton class (Listing 4).
project in the Package Explorer pane. In that directory, Once the application receives the BUTTON_CLICK event,
you should see your swc, if you do not, try right clicking it calls the updateText function. This function looks into
on the libs folder and selecting Refresh. the component and gets the x position of the track
In the MXML editor, switch to Design view. When thumb then puts that value into the text input we set up
the Design view becomes active, the Component earlier.
pane should become available in the lower left of the So now we have communication coming out of the
workspace. The first folder in the pane is the Custom component using the dispatchEvent call in the class.
folder and our custom component should be displayed We are also looking into the component where the
in the list. Drag an instance of this component onto the application is getting the x position of the thumb
stage. track inside the component. Communication can get
To show that we can have two way communication much more complicated than this, but this is a simple
with the component, drag a label and a text input onto example to give a starting point to create more complex
the stage. Set the label's text to be The position of the components.
track thumb is: and move the text input near the label. Click debug to run the application and if no errors
Set the id of the text input to pixelText (Figure 7). Switch occurred, the application should launch in a browser
back to the Source view after saving. window. If you have a browser window open before
Notice that several lines have been added to the running the app, you should close it. There is a bug
source of the MXML document. In addition to the in the Flash Player at the time of this writing that may
MXML for the component including our custom cause the app to not run if there are browser windows
component, a name space value has been added to the already open.
s:Application tag designated as xmlns:test="com.test.*" Once the application is running, click on the buttons
(Listing 3). If we add more components using the and watch as the value in the text input increase and
same com.test package declaration, they will all decrease. The custom component is now complete and
fall under this name space. If we were to add more ready to have more behaviors and methods added to
components using a different package, additional it.
name spaces would be added. You will also notice
that the component starts with test:SliderButton as Conclusion
opposed to s:, fx:, or mx:. While the components that come with Flash Builder can
In the application tag, add an initialize property calling cover most situations, there will be times where only
a function called init(). After the fx:Declarations tags, a custom component will fit the application's needs.
add fx:Script tags to hold the Actionscript. As you type Creating a custom component takes a little work, but
fx, the code completion should pop up and allow you to can make the developer's job a lot easier. With this
select the fx:Script tags. new level of control over the look and behavior of the
Add an id property to the SliderButton tag and give component can make the application more rich and
it a value of sliderButton. In between the CDATA tags, engaging to the end user.
add the init function. This function simply adds an
event listener to our component calling the updateText

LOUIS DICARRO
Louis DiCarro is a consultant based in NYC and has
been working with Flash since the �rst version. He has
taught web development at the college level and has
worked for numerous large clients. He can be reached at
Figure 7. Components on the stage louis.dicarro.ffd@gmail.com.

03/2010 (11) 51
COMPONENTS

AIR Components
in Flash Builder

Adding file and html rendering can result in a lot of code.


But with the AIR components in Flash Builder 4, this
functionality can be added easily with only a few lines of
code.

What you will learn… What you should know…


• What components are available for AIR applications in Flash • Flash Builder 4
Builder 4 • Actionscript 3

W
e already know that building an AIR visual interfaces for interacting with the file system and
application affords us a lot more capabilities a HTML component for displaying web content.
than working with a web based project. You may wonder why these components are only
Digging through the Actionscript documentation shows available for AIR applications. Mostly, it is for security
that there are a lot of classes that are only available reasons. Up to Flash Player 10.1, a swf does not have
to AIR applications. These mostly have to do with the permission to interact with files on the file system
classes and methods that interact with the file system except in very limited circumstances.
or windowing of the application. Swfs in the web browser are able to interact only
Flash Builder, as with Flex Builder before it, contains with files on the server in which the swf is hosted. This
several components that are only available to use allows them to load images, xml and other file types
with AIR applications. These components deal with at run time but only if the files come from within its

Figure 1. AIR Actionscript 3 special classes for the HTML component Figure 2. Layout of the HTML application

52 03/2010 (11)
AIR Components in Flash Builder

We're going to take a look at couple of simple


Listing 1. MXML of components
examples for each component to get a feel how use
them. It is also important to note that the documentation
<s:TextInput id="addressBar" x="10" y="10" for these components are in the AS 3 documentation.
width="518"/> When looking at the documentation, you will see
<s:Button id="goButton" x="555" y="13" a symbol next to some of the classes and also next to
label="Go" click="goButton_ some methods within the classes (Figure 1).
clickHandler(event)" />
<mx:HTML id="htmlPane" x="10" y="40" width="620" HTML Component
height="430"/> The HTML component is very easy to work with. It can
pull in many types of media and render them as you
Listing 2. goButton handler would expect them to be rendered in a web browser.
Start up Flash Builder and create a new Flex project.
protected function goButton_clickHandler(event: Name the project and select Desktop under project type.
MouseEvent):void Click finish and let Flash Builder set up the project.
{ Once the project is started, click on the Design tab,
htmlPane.location = addressBar.text; In the lower left a component tab should be open. If it
} is not, open it using the Window menu and selecting
Components. Scroll down to the Adobe AIR folder. You
own sandbox. There are exceptions and ways around will not see this folder if you set your project to run in
it, but for the majority, the swf cannot interact with the a web browser.
file system. We are going to create a simple web browser using
If the development of applications using Flash only three components and one line of code. First, drag
Builder and AIR were to succeed, they would need a HTML component, a text field and a button to the
to act like real desktop applications. This means that stage. Arrange them how you would like and switch
the applications would have to load and save files just over to design view.
as any other application that a user would use on the Give each component an id as in Listing 1. Also, give
computer. the button a click handler. Type click and let the program
Security is still maintained in this model by having auto complete, another code hint will pop up to create
the developer digitally sign their application using the handler automatically.
certificates. If the certificate is obtained though a trusted Flash Builder will generate the handler as well as the
source, the application would be traceable back to the fx:Script block in the code. In the click handler that is
original developer if something bad should happen. generated, add a line that will set the location of the
Having a HTML component gives the application HTML component to the text in the text field. See Listing
greater rendering power by tapping into the Web Kit 2 for the full code.
which can run better than the HTML renderers in the Run the application and fill in a valid web address in
Flash Player. This allows developers to repurpose the application. Remember to include http:// in front of
content from their web site to the application.

Figure 3. The application running Figure 4. Layout of the image viewer application

03/2010 (11) 53
COMPONENTS

Create a new Flex Project as we did before and be


Listing 3. MXML of components
sure to make it a desktop application. Once the project
has loaded, switch to design view and drag a File
<mx:FileSystemTree id="fsList" x="10" y="10" System Tree and an Image component to the stage.
height="460" change="fsList_ See Figure 4 for the layout.
changeHandler(event)"/> Once the application is laid out, switch over to the
<mx:Image id="imgPane" x="193" y="10" width="437" Source mode and give all the components ids as we did
height="460"/> before (Listing 3). Also add a change handler instead
of a click handler. Flash Builder will autocomplete and
Listing 4. Handler for change event generate the handler for you as it did when we added
the click action to the button.
protected function fsList_changeHandler(event: In the generated handler, add the code that will
ListEvent):void load the image into the image component. To keep
{ everything simple, we only are going to load jpg and
var file:File = event.currentTarget.selectedItem png files (Listing 4). in this function, we are first checking
as File; to make sure the file is a file and not a directory by
if(file.extension) checking for a file extension. If the file passes the first
{ test, we check to see if the file is a jpg or png. Lastly, if
if(file.extension.toLowerCase() == "jpg" || the file passes all of these test, it gets loaded into the
file.extension.toLowerCase() == image component.
"png") Save the file and run the application to see the
{ results. Clicking on the file system tree items will
imgPane.source = file.url; either open or close the directory or try to load the file.
} When the user clicks on a jpg or png, it will load into
} the image component (Figure 5). Note that as the tree
} expands, a scroll bar is attached to the component
automatically.
the address. Click the Go button and the page should
load after a few seconds. Take a look at Figure 3 for the Conclusion
results. Just as with the HTML component, there is more
There are a lot of methods and commands associated methods and properties available to you with the file
with the HTML component. This will allow you to make system components. In this demo application, we have
a more customized display and give more control over seen how easy it is to get access to the file system
the HTML content that you show. using the component without writing a lot of code.
There is a lot more involved in making a full application
File system components using these components, but we have witnessed how
Using the file system components is just as easy. To test easy to get started with them. Having more control over
the components, we are going to create a simple image the elements as well as error checking would be added
viewer that allows the user to select the images from in real applications.
the file system. Having these components available gives the
application a large amount of functionality very quickly
and allows the developer to concentrate on the logic
of the application. Using these components in your
application will help make it more full-featured and feel
more like a real desktop application.

LOUIS DICARRO
Louis DiCarro is a consultant based in NYC and has been
working with Flash since the �rst version. He has taught
web development at the college level and has worked for
numerous large clients. He can be reached at:
Figure 5. The image viewer application running louis.dicarro.ffd@gmail.com.

54 03/2010 (11)
TLF

Applying CSS
to Text Layout Framework styles

This article is a reply to our reader’s question about the


possibility to apply CSS to Text Layout Framework (TLF). We
will show how to implement the necessary class and switch
text styles on the fly.

What you will learn… What you should know…


• how can custom styles be applied to TLF elements • the basics of Flex and Flex/Flash Builder
• how to implement IFormatResolver to work with CSS • the basics of TLF

T
LF is introducing the new way of applying styles Listing 1 shows the complete implementation of the
to the text. Prior to TLF, flash used simple class, and will we look closer into it later. For now, pay
approach: you had to prepare and attach attention on the following functions:
StyleSheet object to the style property of the TextField.
TLF provides more flexible and customizable, but • invalidateAll
more complex technique. • invalidate
During this tutorial we are going to create a small • resolveFormat
application in Flex 4. This application contains a text • resolveUserFormat
displayed with TLF component TextArea and 2 different • getResolverForNewFlow
CSS, that can be applied to the text simply by pressing
the button. Figure 1 show the screenshot of the These function are created automatically by Flex
application. Builder as they are required for implementation
of the interface. All functions are callbacks that
TextFlow and it’s IFormatResolver are called when the certain action is performed
TLF provides a callback mechanism to for with text by TextFlow and it needs to know how to treat with
styles. TextFlow object’s got a property formatResolver different elements.
that should implement IFormatResolver
interface. Actually it is a set of
callback functions that are called by
parent TextFlow when it processes it’s
elements.
To have a closer look at formatResolver
we will implement it’s version to work
with out simple CSS. So start, create
a new project in Flex and name it,
for example, TextCSS. In the default
package create a new ActionScript class
named CSSFormatResolver that implements
IFormatResolver interface. Figure 1. Style changing application

56 03/2010 (11)
Applying CSS to Text Layout Framework styles

For our case, we are interested in resolveFormat Main Application


function that is called for every element of the TextFlow, Listing 2 contains a full code for main application.
when it’s style needs to be changed. This function return The application consists of:
an object that should implement ITextLayoutFormat.
Before we continue, lets have a fast look at main • TextArea with some text. The text is formed
application and how we build our example. using XML. Some elements of the TextFlow have

Listing 1. CSSFormatResolver.as

package format.color = style["color"];


{ format.fontSize =
import flash.text.StyleSheet; style["fontSize"];
format.fontWeight =
import flashx.textLayout.elements.FlowElement; style["fontWeight"];
import flashx.textLayout.elements.FlowValueHolder; format.fontStyle =
import flashx.textLayout.elements.IFormatResolver; style["fontStyle"];
import flashx.textLayout.elements.TextFlow; }
import flashx.textLayout.formats.ITextLayoutFormat; }
}
public class CSSFormatResolver implements return format;
IFormatResolver }
{
private var _styleSheet:StyleSheet; public function resolveUserFormat(target:Object,
userFormat:String):*
public function CSSFormatResolver() {
{ return null;
_styleSheet = new StyleSheet(); }
}
public function getResolverForNewFlow(oldFlow:
public function invalidateAll(textFlow: TextFlow, newFlow:TextFlow):
TextFlow):void IFormatResolver
{ {
} return null;
}
public function invalidate(target:Object):void
{ public function get styleSheet():StyleSheet
} {
return _styleSheet;
public function resolveFormat(target:Object): }
ITextLayoutFormat {
var format:FlowValueHolder = null; public function set styleSheet(value:StyleSheet):
void
if (target is FlowElement) { {
var element:FlowElement = target as _styleSheet = value;
FlowElement; }
if (element != null) { }
format = element.format as }
FlowValueHolder;

if (element.styleName != null) {
var style:Object = styleSheet.getSt
yle(element.styleName);

03/2010 (11) 57
TLF

Listing 2. TextCSS.mxml

<?xml version="1.0" encoding="utf-8"?>


<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" <s:TextArea x="10" y="10" width="285" height="86"
xmlns:s="library://ns.adobe.com/flex/spark" id="css1" >
xmlns:mx="library://ns.adobe.com/flex/halo" <![CDATA[
xmlns:local="*" h1
width="640" height="300"> {
color:#FF0000;
<fx:Script> fontSize:20;
<![CDATA[ fontWeight:bold;
import mx.events.FlexEvent; fontStyle:normal;
}
protected function applyCSS1Button_
clickHandler(event:MouseEvent):void h2
{ {
var formatResolver:CSSFormatResolver = color:#FF00FF;
new CSSFormatResolver(); fontSize:16;
formatResolver.styleSheet.parseCSS(css1 fontWeight:bold;
.text); fontStyle:italic;
textArea.textFlow.formatResolver = }
formatResolver; ]]>
</s:TextArea>
}
<s:TextArea x="345" y="10" width="285" height="86"
protected function applyCSS2Button_ id="css2" >
clickHandler(event:MouseEvent):void <![CDATA[
{ h1
var formatResolver:CSSFormatResolver = {
new CSSFormatResolver(); color:#00FF00;
formatResolver.styleSheet.parseCSS(css2 fontSize:32;
.text); fontWeight:normal;
textArea.textFlow.formatResolver = fontStyle:italic;
formatResolver; }
}
]]> h2
</fx:Script> {
color:#0000FF;
<s:TextArea id="textArea" width="620" height="134" fontSize:24;
x="9" y="156"> fontWeight:bold;
<s:TextFlow> fontStyle:normal;
<s:p styleName="h1"> }
Title of the Text ]]>
</s:p> </s:TextArea>

<s:p styleName="h2"> <s:Button x="108" y="105" label="Apply CSS


Section of the Text 1" id="applyCSS1Button"
</s:p> click="applyCSS1Button_
clickHandler(event)"/>
<s:p> <s:Button x="443" y="105" label="Apply CSS
This is a body text. Lorem ipsum... 2" id="applyCSS2Button"
</s:p> click="applyCSS2Button_
</s:TextFlow> clickHandler(event)"/>
</s:TextArea> </s:Application>

58 03/2010 (11)
Monday
Tuesday
got styleName attribute, so you could apply the
corresponding CSS style to them later.
• 2 TextAreas with simple different CSS.
• 2 Buttons to apply CSS from TextAreas to example
text.

Wednesday ?
When the button is clicked, the new instance
of CSSFormatResolver class is created. Then the
corresponding CSS string from the TextArea is parsed
and set into resolver’s property of SlyleSheet class
type. And finally, prepared formatResolver instance is

Thursday ?
assigned to the TextFlow.

Applying CSS to TextFlow


Now, lets have more detailed look at resolveFormat
callback function. First, it should return a value that

Friday
implements ITextLayoutFormat, if it returns null, then
no new styling should be applied to an element being
processed by the function. So, we create format variable
of FlowValueHolder (it implements ITextLayoutFormat) and
set it’s value to null (we do that, because resolveFormat
works with all elements, including TextFlow itself, as
probably we don’t want to apply one style to the whole
text).
After we do all the necessary casts and null checks,

����������������
and if we are sure that current element’s got styleName
attribute, we assign styles from CSS to a current format.
StyleSheet object is used to contain CSS data, as it is
convenient object to parse and retrieve CSS data.
��������������������������������������
Conclusion and a Warning ������������������������������������
There was a brief tutorial on how to apply simple CSS
to TLF TextFlow. Please, note, that CSSFormatResolver ������������������������
class is not fully functional and only can be applied to
�����������������
our sample CSSs. Writing reusable and versatile class
requires more detailed coding and approach.
�����������������������������
Check the TLF Blog on this issue. There is fully �����������������������������
functional CSSFormatResolver with example there: http: �����������������
//blogs.adobe.com/tlf/2009/02/iformatresolver_and_ �����������������������������������������
using_css_1.html.
�������������������������
��������������������������������������
���������������������������

���������������������� �������������������
���������� ���������� ����������

�����������������������
������������������������������
MAXYM GOLOVANCHUK
Maxym Golovanchuk is a Photoshop Certi�ed Expert and TV
producer, and he is using Adobe’s software for implementing
entertainment solutions, including video delivery with Flash
Media Server. mexxik@gmail.com

DIVISIONS OF CREATIVE NICHE INC.


03/2010 (11) 59
PROFILE

Flashcreed – Business Gallery


Hello it’s good to be back here among Flash & Flex
Magazine readers. Today we are going to tell you a bit about
our products, mainly our Business Gallery but since all our
products are built on the same framework, most of the
properties apply to all. When we first realized what we could
do with this framework, we decided to name it “Pandora” in
order to point out the unlimited number of possibilities it
revealed regarding customization and user friendliness.

T
he Business Gallery (http://www.flashcreed.com/business_video_image_gallery) is a Flash
component meant to do one thing: to enhance the visual experience a website portfolio or
presentation site gives to its users. Mainly it’s all about the image you present yourself or
your product to the world wide web. Let’s face it, without the looks you can’t sell your product or
image no matter how interesting it might be.
What’s so great about this gallery you might wonder? Well, the answer is simple, everything.
Advanced AS3 programming, dynamic XML implementation, unlimited number of media items on
stage, PNG, JPG and video: FLA, SWF, MP4, F4V supported media, tween and image effects just
to name a few of the over 150 settings this gallery brings you. Bottom line, you can customize it
in any way you see fit in order to make it resemble your website layout. Not to mention the code
optimization that allows the gallery to run so smoothly even on low resources.

We brought 45 background wallpapers in case just a color doesn’t do the job, also a set of custom arrows
and close buttons.

60 03/2010 (11)
Flashcreed – Business Gallery

The size of the entire gallery and any element in it is subject to any kind of resize, big stage and small thumbs
or the other way around for any template you or your client desire.

Column_scroll and the properties for the stage mask helps you configure the exact number of visible columns
you want to set in order to browse through the media items your gallery has. Beside this useful feature, we
added blur and a couple of tween effects for the left/right navigation that gives an impressive look.

03/2010 (11) 61
PROFILE

The color gradient system for roll over/out mouse gesture is unique in every way if we are to compare it with
other galleries on the market at this point. You can customize up to 5 sets of color with different alpha values.
The gradient type, either linear or radial, can be modified with rotation and ratio values.

Either as tooltip or plain text, you can show any information you want regarding a certain media thumb in the
gallery. You can change font type, size, spacing, color, position and many other properties.

62 03/2010 (11)
Flashcreed – Business Gallery

When clicking on a thumb if preview_type is selected as internal, a resizable preview window will reveal itself
and depending on the media type (image or video), an image viewer or video player will be contained inside it.
If preview_type is selected as external, you have the possibility to set certain URL addresses this allowing you
to redirect the user to a specific area of the website, like a product page from a virtual store for example.

The video player has a dozen of controllers that allow you to create a skin to better suit the template you want
to create for your gallery. Button’s color, thickness, handler color or scrub bar size, just to name a few of the
properties you can play with.

At an amazing price of 9.99 $, this has to be one of the best choices when it comes to media
galleries flash components. Don’t hesitate to take a look at it on www.flashcreed.com and
also consider other products that might better suit your specifications or desires. We would
definitely appreciate any kind of feedback regarding current or possible features.

Thank you!

03/2010 (11) 63
BOOK REVIEW

Essential Guide to Flash Games

Authors: Jeff Fulton, Steve Fulton


Publisher: friends of ED.
ISBN: 978-1-4302-2614-7
Language: English
Pages: 664 Pages
Website:
http://friendsofed.com/book.html?isbn=1430226145

A
re you an actionscript 3 game developer who developers but also Flash Develop users. In addition
is not able to write a complete commercial to this, you will also learn to create game assets
game because you cannot manage dozens with GIMP, Mappy and a sound effect creation tool.
of classes? Or you are an experienced actionscript 3 You will get information about copyright laws which
applications developer who wants to program game are necessary for any would-be commercial game
but don’t like reading any available beginner book as it creation and a complete game example integrated
doesn’t suit your style. Even if you already have a good with MochiAds.
grasp over java or c++ and interested in creating not This book also discusses and further more implements
only fun games but commercial ones also, then this is various advanced topics such as bitmap rendering,
what you really require pixel-level collision detection, sound management,
There are several actionscript 3 game development AI, xml-based level designing, scrolling, screen
books for beginners out there, but Essential Guide optimization techniques, particles etc.
to Game Dev is one of those few books that talk In short, this book will surely blow your minds with
about the advanced gaming concepts. However the wealth of knowledge it includes and you will pray
its first chapter begins with an easy to understand for authors to keep writing such informative and useful
game example (good for any beginner) and ends up books.
creating 3 games. Did I tell you 3 games in just first If you are really serious about gaming then don’t
chapter? miss the opportunity of reading this book. Highly
Teaching about an Actionscript 3 Game framework recommended.
is one of the many reasons that make this book a kick-
ass addition to actionscript 3 gaming library. Authors by Ali RAZA ACI, ACE, SCJP
teach you how to create 10 unique games ranging
from arcade to driving, tile based to puzzle game and
shooters to dice games. Another specialty of this book
is to use Flex and Flash Develop IDEs along with the
primary Flash tool that creates space for not only flex

65 03/2010 (11)