Escolar Documentos
Profissional Documentos
Cultura Documentos
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™
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
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
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 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
03/2010 (11) 9
IN BRIEF
10 03/2010 (11)
IN BRIEF
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.
03/2010 (11) 11
TOOLS
Storyfarm Switches to
G-Technology™ G-SPEED™ eS PRO to Cut Latest Doc Projects
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.
03/2010 (11) 13
BEGINNERS
Working with
Display Objects 101
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
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
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.
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;
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
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:
18 03/2010 (11)
ACTIONSCRIPT DEVELOPMENT
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
22 03/2010 (11)
Creating an AS3 Game Framework
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.
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);
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);
}
28 03/2010 (11)
Creating an AS3 Game Framework
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.
30 03/2010 (11)
ACTIONSCRIPT DEVELOPMENT
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).
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
03/2010 (11) 33
ACTIONSCRIPT DEVELOPMENT
Listing 1. gallery.xml
34 03/2010 (11)
ACTIONSCRIPT DEVELOPMENT
Listing 2. PhotoGallery.as
36 03/2010 (11)
Creating an XML Photo Gallery with AS3
Listing 2. PhotoGallery.as
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 (); }
enableNavigation ();
}
38 03/2010 (11)
Creating an XML Photo Gallery with AS3
Listing 3. ThumbNail.as
03/2010 (11) 39
ACTIONSCRIPT DEVELOPMENT
Listing 3. ThumbNail.as
40 03/2010 (11)
Creating an XML Photo Gallery with AS3
Listing 4. BigPhoto.as
// 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
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.
44 03/2010 (11)
COMPONENTS
package com.test
{
import mx.flash.UIMovieClip;
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.events.MouseEvent;
import flash.filters.GlowFilter;
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
48 03/2010 (11)
Custom Flash CS4 Components in Flash Builder 4
xmlns:test="com.test.*"
<test:SliderButton x="14" y="10" id="sliderButton"
/>
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.
<fx:Declarations>
<!-- Place non-visual elements (e.g., services, value objects) here -->
</fx:Declarations>
<fx:Script>
<![CDATA[
]]>
</fx:Script>
50 03/2010 (11)
Custom Flash CS4 Components in Flash Builder 4
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
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
Figure 3. The application running Figure 4. Layout of the image viewer application
03/2010 (11) 53
COMPONENTS
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
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
Listing 1. CSSFormatResolver.as
if (element.styleName != null) {
var style:Object = styleSheet.getSt
yle(element.styleName);
03/2010 (11) 57
TLF
Listing 2. TextCSS.mxml
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.
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
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
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)