Tag Archives: as3

I hope 2011 will be a successful year!
This post is mostly targeting to developers who like to dive deeper into actionscript and are searching for a another way to start a project, and not so much for the newbies to web design or those just starting out in online web design degree programs. In my opinion there are missing a lot of these types of posts, so I just share mine. This post is a collection of post I have never posted in 2010. I hope it will trigger more flashdevelopers to share there view on this topic. Disclaimer: There are several ways to start a flashproject, and I don’t think my examples are the best way, but I hope they challenge you to think about your setup. In case you work in a webteam, it’s important to work in a way that is understandable and transparent. You should talk to each other what you really need and expect from each others code.
Use existing frameworks (?|!)
There are companies who use very transparent architecture frameworks like PureMVC or RobotLegs, others use there own frameworks and build on that. Personally I don’t use that big frameworks (yet) as architecture base, because I don’t create that large applications/sites and for now its more overkill than helpful I guess. There are also some helper frameworks like casalib and templelibrary around, which can provide you a set of (util-)classes and interfaces. This post is not created to discuss if its better or not to use these already accepted frameworks. If it fits your needs and you want to standardize flash coding; just use it; they are great and very helpful. At the other hand some (mostly larger) frameworks are hard to understand and requires some learning curves / basic skills. I am currently working on flashflowfactory, which is designed to be an easy-to-learn framework, mostly for medium/small websites which needs deeplinking and page transitions; you should check it out. So at the other hand, it is cool to create your own framework and you will learn a lot from it, but there is already lots of good stuff on the internets.
Building
Get your tools
For most projects I’d love to use FlashDevelop. It’s my code editor of choice. I’m Dutch and this is a free tool, so there is no need to look at other tools
Download and install it and follow the instructions. Install the latest debug activeX player and download the latest Flex SDK. After you tried FlashDevelop for a while, just donate some money to support the project. Even if your Dutch. Just give back. Oh, and download the duplicate plugin and you don’t want to switch to another tool ever.
Setup of the site assets
I love to store my assets inside an SWC, which are viewable (with some logic) in Flash IDE too. Mostly I use the Flash IDE to generate an SWC. All my ‘views’ like pages, vectorimages, bitmaps, icons and advanced animations are stored inside that SWC. This of course except the assets I want to load from external sources. I don’t use much code on the timeline, except some play/stop()-commandos, because it stopping an animation cannot be done more clear than on the timeline. I don’t feel ashamed anymore to say that I sometimes put code on the timeline (think of a preloader, framelabel jumps etc). As long as you keep the project structured, this should never be a problem. All my views (that need to be accessible from code) are linked to external classes. In this way I can get the most out of the Flash IDE too; there are lots of animation- and designthings that cannot be done quickly with code. So don’t forget the Flash IDE; It’s a really powerful tool. Don’t loose your creativity on code only.
So what is the plan?
It’s important to plan your website/application. If you want to be serious, at least just make a small plan. In case of a webteam: Make a checklist what should be done, where you are currently working on and what is done. Having a list of todo’s helps to be more open. In case of a personal project: Most projects fail if you don’t write things down, because you loose overview and also the interest for your potential killer-app. Just break things down into small peaces.
Getting control
What do you need to get started?
Some people start creating cool UML diagrams, others just grab some piece of paper. Others start in Photoshop creating the design rightaway, but it would be helpful to create a wireframe in some cases. What the most important thing is, is to be aware of what you are going to create and which classes you need. Don’t start to think about the features (yet), think plain. What is the essence of this app? What does it needs to do before it ‘works’? What is needed to get to this point, and how would you built it? Think about how to setup a useful way for navigation. You want to use deeplinking? At what point/place should this happen? What kind of events do we need? Are there recurring elements? Which things should be (dynamic) components, what should be fixed/hardcoded? Which creative parts are hard to develop, and which parts should be more creative? Also add to your todo-list the hours you think it would take to build it; you get more awareness of how to deal with time managing.
Start collecting puzzle pieces
It’s time to collect things we need. It maybe sounds stupid, but why wouldn’t you start with collection the global things? These things are important. Think about if you want to use frameworks and which parts you would code yourself. Are you going to use programmatic tweens? You could use a tween engine. Create a basic HTML file, embed the flash already. Create your package-structure. I don’t know if its is the way, but I love to write down stub- or pseudo code. Create as much empty classes which need to be filled. Keep in mind you need to refactor a lot of times if you start like this, but I don’t mind. This forces me to keep thinking about the structure, refactoring is a good thing, right?
Learn from the past; find recurring elements
Now I have created a mini framework for setting up a website with pages. In my professional life I use Flash to create a lot of viral websites. Most of the pages are not the same, every design is different and has it’s own ‘thing’. So most of the times I find it difficult to fit this into a system. At the other hand, I like to prevent to have too much abstract classes; I want too keep things clear. However the challenge is to find the recurring elements and create a system which can be reused later. This is one of the reasons why I am developing flashflowfactory. Some examples; I always want to have deeplinking, I want to have a transition when I go from page A to page B. And I would love to have the ability to go from page A to page C etc. I also want to send simple events/notifications to anywhere in the application. Well the framework covers that already, however it is still in progress. I love to keep its simplicity in usage, but also the fact I already used it in multiple projects and it slowly satisfies my everchanging needs.
Keep the freedom
From the coding perspective, I love to have a structured project, even if the designs are not that consequent. Mostly I start with creating the raw pages. These are mostly the starting point. I have already said I am using SWC’s for the views; I point the base Class of a MovieClip to my classfiles (.as). Inside my class file I say it extends Sprite. As Classname I mostly give the same path, only I add VC (ViewComponent) after the name. For example; When creating a contact page, I use ‘ContactPage‘ as base class, and ‘ContactPageVC‘ as class name. This allows me to add the view from code (by adding the view-component) or to just put it directly from the library on the stage inside the Flash IDE. Yes, it is a bit pain in the ass to apply this to lots of pages/components, but it gives freedom of how to use your assets. If anyone knows a better/more simple solution, let me know!
Happy 2011!
Please share your thoughts.
I am working very hard for the first release of flashflowfactory. There are lots of code tweaks and more improved documentation already. More about the framework and some introductions can be found in this earlier post. Now I really want to make it easy for lots of people. I already got some helpful tips from users/testers. So I am collecting everything that is needed to make it as usable as possible. I am working on demo projects and it is still alpha.
Serving as SWC
Nowadays every AS3 framework is being served as SWC. This makes it very easy to add it to any project. So I really needed to create this too
However I thought it was easy, but I stumbled to a little problem:
I am using TweenLite, but is is not legal to serve code from GreenSock/TweenLite on googlecode, because of the special license model. Now all the flashflowfactory transitions make use of TweenLite. So when I would like to create an SWC of the framework + the transitions, I must include TweenLite. So, and that is the only option, I need to serve the transitions as a separate package. This makes me think. I am using TweenLite because it is my favorite tweenengine. I could use another tween engine, with a MIT license. But then the users of the framework should fully switch to that engine, or include multiple tweenengines in their projects (which would be crazy). So the new plan is to create an SWC of the framework without any default transition. Then I will serve multiple packages with the default transitions ported to some famous tween-engines, so you could make a choice. If you want to use Tweenlite you should download the TweenLite pack etc.. I have created the packs for TweenLite, Tweener, gTween and eaze-tween.
I thought this whole license-thing was a problem, but when I take a closer look; Now you can make use your own favorite tweenengine. I think more choice is better (in this case).
Check it out now:
- flashflowfactory.stroep.nl
- Googlecode project
- Documentation / Simple how-to
Previous year I was working on a little class called Chain. Chain is a delayed function-calling util class for AS3. Now I was already working at a updated version which could animate too (see this tweet from last year). Basically it has become a small tween engine. You have to know there are much better tween engines, like TweenLite, Tweener, eaze tween, gtween etc.. So you don’t need a new tween engine, and definitely not this one
I just love to share some thoughts.
I just finished this to see how far I could come and where I have to deal with by creating such an engine. It is just fun to develop classes which will bring you to a higher level of coding, because I really want to become an actionscript sensai master or something. When starting the animation part, I was very inspired by this post, which has the same idea of combining jQuery-syntax-style with tweening, which I was already using in Chain.
Making a class chainable is very easy, you just have to return the class instance on every public function, like this:
package
{
public class ExampleChain
{
public function add():ExampleChain
{
trace(this, "saying hi!")
return this;
}
}
}
This already allows you to do this:
var chain:ExampleChain = new ExampleChain();
chain.add().add().add().add();
I think this is very powerful and we should use more chaining.
Anyway, Chain was originally created to make delayed function calling. I wrapped code around this feature, so it is still usable like it was intended, only I improved some functions and added tweening. You can pass a complete handler to the play() function. And it is also possible to reverse the full chain, even with animation.
Here again, the original simple usage
var myChain:Chain =
new Chain
();
myChain.
add(one,
2000) .
add(two,
500) .
add(three,
1000) .
play(3, onChainComplete
);
// play 3 times// some functions
function one():void { trace("one") }
function two():void { trace("two") }
function three():void { trace("three") }
function onChainComplete():void {
trace("done.");
myChain.destroy();
}
/* trace output:
one two three one two three one two three done.
*/
Animated chain example
var myChain:Chain =
new Chain
();
myChain
.
animate(myMc,
{x:
300,y:
100},
700, Easing.
elasticInOut) .
wait(200) .
animate(myMc2,
{rotation:
100, alpha:
0.5},
500, Easing.
quartIn) .
wait(200) .
play(2, onChainComplete
);
// play 2 timesfunction onChainComplete():void {
trace("done.");
myChain.destroy();
}
As you can see, you can still chain things, it animates multiple movieclips, and it can be played multiple times. It is very readable, which I really like. It works also in reversed order too, so you can reverse the full animation (pointless but cool)!
If you don’t want to animate, but instantly apply settings to a displayObject,
you can use apply(mc, {vars}), of couse this equals animate(mc,{vars},0) but it is more elegant.
To control the Chain, you have can use:
stop() Stop playing, use doContinue to play futher from current point
doContinue() Continue playing after a stop
reset() Reset indexes, start from first point. If reversed, start at last point
So how does it work? Well it is still based on the same old add() function. When you call the animate() function, internally, it is collecting the properties of the tween. Then it is calling the add() function, with a reference to a protected function playTween(), which is always the same. So when you play the chain, it just calling a local function every time, which handles the animation.
For now, I don’t have any special properties; no auto-alpha, no short-rotation, blurfilters or tinting etc. You can only animate properties of movieclips.
So how does tweening (animation over time) work? This is the formula I am using:
_target[property.name] = property.startValue + ((property.endValue – property.startValue) * _easeFunc(currentTime – _startTime) / _duration);
This needs a little explanation. For example: When you add {x:100} as object to Chain for animation, “x” is the property.name, and 100 is the property.endValue. I am also getting current “x” value of the displayobject (which should move); this is the property.startvalue. Imaging this is currently 75.
If you would write down the values into the formula, it looks like this:
myMc["x"] = 75 + ((100 – 75) * _easeFunc(currentTime – _startTime) / _duration));
Now, as you can see, this is more readable. The only thing that is still vague is the ease function. Now I have to say this was a bit hard for me to understand at the first time, but it became very clear when I did understand what is does. I have read the book ‘Making things move’ from Keith Peters (aka bit-101), which is a great reference and eye opening book for programmatic animation, trigonometry and other cool stuff. There is a chapter where animation over time is explained, which was really helpful creating the tween engine, and this time calculation. Now the time calculating returns a ratio, which is needed for the easing functions. I also studied some famous other tween engines; most of them use basically the same formula. By the way, the easing equations are used from Robert Penner.
Now, I really wanted to reverse the animations too. After some headache, the solutions was very simple. The time calculation is a value between 0-1, so I did 1 minus the time ratio 
_target[property.name] = property.startValue + ((property.endValue – property.startValue) * _easeFunc(1 – (currentTime – _startTime) / _duration));
Another problem I had to deal with was the fact that animating 1 thing at a time is very boring. So I invented the animateAsync(), which works almost exactly like the animate(), only you could pass the duration and the delay as separate values. So you can move a clip for 700 milliseconds, and call the next chained item after 75 milliseconds. To compare: when using the animate() function, if you move an item for 700 milliseconds, it will take 700 milliseconds when calling the next chained item. This could cause strange behaviors and isn’t easy to manage (especially when you want to wait till all animations are done), but I its a nice feature I think. Again, even the async’s can be played in reversed order.
var myChain:Chain =
new Chain
();
myChain
.
animateAsync(myMc,
{x:
300,y:
100},
700,
10, Easing.
elasticInOut) .
animate(myMc2,
{rotation:
100, alpha:
0.5},
500, Easing.
quartIn) .
wait(200) .
play(2, onChainComplete
);
// play 2 timesfunction onChainComplete():void {
trace("done.");
myChain.destroy();
}
To clear all references, you should call the myChain.destroy(); function. This clears the references to all added functions, and clears the internal tween list.
update 02/11/2010:
- added show/hide/rotate function
- added shortRotation option
- added scale (no need to define scaleX and scaleY separately)
- optimized chain; chain items are stored by duration inside dictionary to save lots instances (where duration is the same)
- added Chain.create for fast creation of an instance
- updated apply function (extra param; apply on start)
- several coding style fixes
- added destroyOnComplete to animate() function
So if you are interested in the code, you can find it inside my googlecode:
» Chain Tween sources
I am a bit proud to present you my first own framework: flashflowfactory.
This mini-framework for actionscript 3 helps you to easily setup a flash website. flashflowfactory makes use of SWFAddress for deeplinking and TweenLite for transitions. When you need to create small/medium websites with deeplinking and basic transitions, flashflowfactory could help you develop faster. I mostly used it for custom projects like viral websites. The best of flashflowfactory is its simplicity (no need to learn hard design-patterns, it is really straight-forward if you know the basics). You don’t have to develop a page setup or start from scratch, but keep the freedom to build the site in your style.
Check it out now:
- flashflowfactory.stroep.nl
- Googlecode project
- Documentation / Simple how-to
Features
- Global page creation
- Deeplinking made easy: it’s included and no need to worry about it anymore
- Page class with transition settings and states
- Transitions between pages
- Currently 4 transitions included
- Creating your own transitions is possible. This keeps your freedom of expression and makes it usable for every custom project.
- Global page settings and these settings can be overrided on page level
- Transition in/out between page
- Easing/time customizable
- Alignment options
- Alternative navigation (button) system
- Really easy linking
- Automatic states
- Grouping aka easy active state
- Global Event system
- Listen to event from any point in your application
- Automatic Event removal system
Example setup code
var pageFactory:PageFactory =
new PageFactory
();
// add your pages here: url, classReference, title pageFactory.
add( "/home", HomePageVC,
"Welcome!" );
pageFactory.
add( "/contact", ContactPageVC,
"Contact us" );
pageFactory.
add( "/info", InfoPageVC,
"About us" );
// optional page name, which indicates where to start
pageFactory.defaultPageName = "/home";
// add default page settings, can also be overridden from the Page class
pageFactory.defaultSettings = new PageSettings(
new SlideTransition(), // transition (there are more transitions + you can easily create your own)
Elastic.easeOut, // easing of the in-transition
Strong.easeIn, // easing of the out-transition
1, // duration of the in-transition
0.7, // duration of the out-transition
Alignment.MIDDLE_CENTER, // alignment of the page on the stage
Alignment.LEFT_TOP // centerpoint position of the page
);
// add page holder to stage
addChild( pageFactory.view );
// load first page
pageFactory.init();
This is the first release. The framework is still under development, and I really need some feedback. Some example projects will follow soon.
I hate removing listeners in AS3. So I created a work-around to autoremove them
I know there are already some solutions for this, but some of them requires a complete new event system and it is just fun to create your own sources. This class overrides the default behavior of the addEventListener function. It stores references of the listeners inside a Dictionary. The class it selfs listens to the REMOVED_FROM_STAGE event, and when it is removed, then it removes all stored events.
UPDATE 11-10-2010: This code below is a bit outdated.
You’d better use this EventManagedSprite and this EventRemover. BTW: This is all included in FlashFlowFactory. This lightweight framework helps you to easily setup a flash website.
package nl.
stroep.
display { import flash.
display.
Sprite;
import flash.
events.
Event;
import flash.
utils.
Dictionary;
/**
* Simple event managing sprite which automatically removes eventlisteners when the sprite is removed from stage. This class should be extended.
* @author Mark Knol
*/ public class EventManagedSprite
extends Sprite { private var eventsList:
/*Array*/Dictionary =
new Dictionary
();
public function EventManagedSprite
() { super.
addEventListener(Event.
REMOVED_FROM_STAGE, onRemoveEventManagedSprite
) } private function onRemoveEventManagedSprite
(e:Event
):
void { super.
removeEventListener(Event.
REMOVED_FROM_STAGE, onRemoveEventManagedSprite
);
for (var type:
String in eventsList
) { var events:
Array = eventsList
[type] as
Array;
for (var i:
int =
0; i < events.
length; i++
) { var eventObject:EventObject = events
[i
];
super.
removeEventListener( type, eventObject.
listener, eventObject.
useCapture );
//trace("Auto removed listener ", type, eventObject.listener, "from", this); eventObject.
listener =
null;
eventObject =
null;
if (events.
length ==
0) delete eventsList
[type];
} } } override
public function addEventListener
(type:
String, listener:
Function, useCapture:
Boolean =
false, priority:
int =
0, useWeakReference:
Boolean =
false):
void { super.
addEventListener(type, listener, useCapture, priority, useWeakReference
);
if (!eventsList
[ type ]) { eventsList
[ type ] =
[ new EventObject
( listener, useCapture
) ];
} else { eventsList
[ type ].
push( new EventObject
( listener, useCapture
) );
} } } }final internal class EventObject
{
public var listener:Function
public var useCapture:Boolean
public final function EventObject ( listener:Function, useCapture:Boolean ):void
{
this.listener = listener;
this.useCapture = useCapture;
}
}
Make sure every class you add listeners extends this class to make the most out of it. Otherwise you just need to remove the listeners yourself. Let me know what you think about it.
Disclaimer: This class does not detect the eventlisteners on the children of the class. These children should extend the EventManagedSprite class too, otherwise you should remove it manually.
Tagged with as3, events, flash.
Quick post here. I’d like to share this very quick way to create an automatic ID or index to your class instances. Mostly I pass an index as parameter to the class instance, or I use a public var to set the index. Using this way it is very easy to create an automatically filled index, since you have to set this up once and never worry again 
Take a look at this code:
package
{
public class MyObject
{
private static var global_index:int = 0;
public const INDEX:int = global_index ++;
}
}
As you see, I have created a static variable global_index, which is always the same to all MyObject classes. I also created a public constant ‘INDEX’, which would be unique in every instance. When the MyObject instance is created the index will be set to the global_index, and the global_index will increase by one. So that’s basically the trick to create the auto-increment index for your AS3 class.
update: Changed global_index to a private static + removed constructor
Tagged with as3, class, snippet.
Quick post here, a simple solution I found to have multiple keys enabled. Maybe most real game developers know better or more elegant solutions, but I found this useful enough to share it with you.
Here we go. Add these variable to your class. This is a Dictionary, which allows you to associate a value with an object key.
private var currentKeys:Dictionary = new Dictionary();
Then, in your constructor or wherever you assign eventListeners, add these (well-known) listeners, with the callback functions:
import flash.
events.
KeyboardEvent;
stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyDown);
stage.addEventListener(KeyboardEvent.KEY_UP, onKeyUp);
private function onKeyDown(e:KeyboardEvent):void
{
currentKeys[e.keyCode] = true;
}
private function onKeyUp(e:KeyboardEvent):void
{
currentKeys[e.keyCode] = false;
}
Inside your enterframe-event or timer (were you want to detect which keys are pressed), you could these kind of detection.
import flash.
ui.
Keyboard;
import flash.
events.
Event;
private function onUpdate(e:Event):void
{
if ( currentKeys[ Keyboard.SPACE ] )
{
tank.shoot();
}
if ( currentKeys[ Keyboard.RIGHT ] )
{
tank.targetDirection -= 0.1;
}
if ( currentKeys[ Keyboard.LEFT ] )
{
tank.targetDirection += 0.1;
}
if ( currentKeys[ Keyboard.UP ] )
{
tank.speed += tank.acceleration;
}
if ( currentKeys[ Keyboard.DOWN ] )
{
tank.speed /= 1.8;
}
}
I found that if you use some 3 or 4+ combinations of keys at the same time, the keyboard events are not triggered anymore, which is a bit of annoying bug in the FlashPlayer. I mean pressing forward and left and shooting at the same time could be a problem? Well; Hope this helps, I think its very easy and a great usage of the Dictionary.
Tagged with as3, game, snippet.