Thursday, August 19, 2010

Transformations in Actionscript 3: Part 3

Today we will learn how to create and apply filters to objects using AS3!

Filters can make your application look significally better, when used correctly and not too much. Filters are often used in games too. For example, adding blur effect to a quickly moving background adds realism. Here we will learn how to create and apply filters dynamically.

Flash.filters package has these basic filters: DropShadowFilter, GlowFilter, BlurFilter, BevelFilter, GradientGlowFilter, GradientBevelFilter. They're called basic, because they do not require matrixes and other complex things for transforming. Each filter here has simple properties that give siple effects to displayed object(s).

You can pass a filter to the object using filters property, which is an array of filter objects. Example:

example.filters = [new DropShadowFilter()];

When an object is given a filter value, it copies the array's data for the object and doesn't create a link to the filters array, meaning that every time you want to change the filters of an object, you have set the filters property again.

Take a look:

var f_dropShadow:DropShadowFilter = new DropShadowFilter();
var myFilters:Array = [dropShadow];

example.filters = myFilters;

Our object now has a shadow. But now we want it to be red, what do we do?

f_dropShadow.color = 0xFF0000

No changes yet, because we did not update the array.

example.filters = myFilters;

Now our object's shadow is red! Let's add a blur filter to our existing object with shadow. We add the filter to our existing filter array using push method and then update our filters.

myFilters.push(new BlurFilter());
example.filters = myFilters;

Remember that you can't push new elements into filters property, as it isn't an Array.

var f_dropShadow:DropShadowFilter = new DropShadowFilter();
example.filters = [f_dropShadow];

// this won't work:
example.filters.push(new BlurFilter());

// but this will:
var myFilters:Array = example.filters;
myFilters.push(new BlurFilter());
example.filters = myFilters;

Remember, that the filter adding order matters. Take a look:


That's all for now! Thanks for reading.

Related:

Transformations in Actionscript 3: Part 1
Transformations in Actionscript 3: Part 2

No comments:

Post a Comment