Applying Filters


Flash Player 8 has built-in runtime effects called filters that you can apply to movie clips, buttons, and text fields. You can apply any combination of the following filter types:

  • BevelFilter

  • BlurFilter

  • ColorMatrixFilter

  • ConvolutionFilter

  • DisplacementMapFilter

  • DropShadowFilter

  • GlowFilter

  • GradientBevelFilter

  • GradientGlowFilter

Filters represent a major advance in the sort of effects that you can apply to Flash movie content. Each of the filter types is configurable. For example, the BlurFilter allows you to specify parameters such as the number of pixels to blur in the x direction and the number of pixels to blur in the y direction. You can adjust those values at runtime as well. That means that you can create animated filter effects. The potential with filters is limitless. So let's take a look at how to start working with filters.

Constructing Filters

To apply a filter, you must first construct an instance of the corresponding class. For example, if you want to apply a drop shadow effect, you need to construct a DropShadowFilter instance. Each of the filter classes is in the flash.filters package. To simplify working with filter classes, it's recommended that you import the class or classes with which you plan to work. For example, if you want to apply drop shadow effects, you can import the flash.filters.DropShadowFilter class as follows.

    import flash.filters.DropShadowFilter;


If you intend to work with many or all of the filter classes, you can use the * wildcard as follows.

   import flash.filters.*;


After you import the class or classes, you can construct instances using the constructor and a new statement. The following constructs a new DropShadowFilter object and assigns it to a variable called dropShadow:

   var dropShadow:DropShadowFilter = new DropShadowFilter();


Each filter class has different parameter lists for the constructor. You can quickly reference that information in the Flash Help documentation. Many of the basic filterssuch as BevelFilter, BlurFilter, DropShadowFilter, and GlowFilterhave default values, so the parameters are optional. For example, the preceding code constructs a DropShadowFilter object with the default values. However, the following code makes a DropShadowFilter instance with an offset of 10 pixels, an angle of 0, a blue color, 50% transparency, and blurred 10 pixels in both the x and y directions.

   var dropShadow:DropShadowFilter = new DropShadowFilter(10, 0, ¬      0x0000FF, 50, 10, 10);


Assigning Filters to Objects

After you construct a filter, you can apply it to a movie clip, button, or text field using the filters property of the assignee. The filters property expects an array of filter objects. Even if you want to assign only one filter to the object, you still must place it within an array before you can assign it to the filters property of that object. The following code assigns a DropShadowFilter instance called dropShadow to a movie clip called exampleClip.

  exampleClip.filters = [dropShadow];


If you assign more than one filter to an object, the filters are applied cumulatively in the order in which they appear in the filters array. For example, the following code applies a DropShadowFilter and a GlowFilter (called glow) to exampleClip.

  exampleClip.filters = [dropShadow, glow];


Because dropShadow appears first in the array, it is applied first. The glow is then applied to the result of the dropShadow application. That means that the glow won't appear around the outline of the original artwork within exampleClip. It will appear around the outline of the original artwork combined with the drop shadow.

Building a Spaceship Game

In this next task, you'll build the first stage of a spaceship game. When the game is completed, it will allow the user to move a spaceship with the arrow keys to try to stay out of the path of meteors. Several filter effects are used to make the spaceship and game play more interesting. In this first stage, you'll add a bevel filter to the spaceship, and you'll add the code that makes the spaceship move when the arrow keys are pressed.

1.

Open spaceship1.fla located in Lesson09/Start.

The spaceship1.fla document contains all the elements necessary for building the game. You'll note that two movie clip instances and one text field are already on the Stage. On the Background layer is a movie clip instance with an instance name of backgroundClip. On the Spaceship layer is a movie clip with an instance name of shipClip. And on the Score layer is a text field with an instance name of scoreField.

2.

Select the keyframe on the Actions layer and open the Actions panel by pressing F9. Then add the following import statement to the script pane.

  import flash.filters.BevelFilter;


The game eventually uses the BevelFilter class to apply effects to the spaceship. To simplify working with the class, import it to start.

3.

Define a variable (collisionClip) that is used throughout the rest of the code.

  var collisionClip:MovieClip;


The collisionClip variable is used to determine whether or not a collision occurred. You'll use the variable in the remainder of the code.

4.

Apply a bevel to the spaceship using the following code.

  var bevelArr:Array = [new BevelFilter()];   shipClip.filters = bevelArr;


The bevel makes the spaceship appear more three-dimensional.

5.

Make the main Timeline a listener for keyboard events by registering it with the Key class.

    Key.addListener(this);


For the spaceship to move when the user presses the arrow keys you must tell Flash Player how to handle keyboard events. You can do that by registering a listener object. When a key is pressed, the onKeyDown() method of the listener gets called. And when the key is released, the onKeyUp() method of the listener gets called. In this case you're registering the main Timeline as the listener object, so you'll define the onKeyDown() and onKeyUp() methods as functions on the main Timeline.

6.

Define the onKeyDown() function as follows:

  function onKeyDown():Void {     if(Key.getCode() == Key.RIGHT) {       shipClip.onEnterFrame = function():Void {         this._x += 20;       };     }     else if(Key.getCode() == Key.LEFT) {       shipClip.onEnterFrame = function():Void {         this._x -= 20;       };     }     else if(Key.getCode() == Key.UP) {       shipClip.onEnterFrame = function():Void {         this._y -= 20;       };     }     else if(Key.getCode() == Key.DOWN) {       shipClip.onEnterFrame = function():Void {         this._y += 20;       };     }   }


The preceding code might appear rather complex, but if you look at it closely, you'll see that it repeats similar blocks of code. As previously mentioned, the onKeyDown() function gets called when a key is pressed on the keyboard. The function uses a series of if and else if statements to determine which key was pressed. If the user has pressed one of the arrow keys, the code defines an onEnterFrame() method for shipClip. The onEnterFrame() method increments or decrements the _x or _y property of shipClip. Which property and whether to increment or decrement the value is determined by which key was pressed. The result is that the spaceship moves when one of the arrow keys is pressed.

7.

Define the onKeyUp() function as follows:

  function onKeyUp():Void {     delete shipClip.onEnterFrame;   }


The onKeyUp() function is very simple in comparison with the onKeyDown() function. When the user releases a key, you want the spaceship to stop moving. You can accomplish that by deleting the onEnterFrame() method definition for shipClip.

8.

Test the movie

When you test the movie you'll see that the spaceship has a bevel applied to it programmatically. If you press the arrow keys, the spaceship moves in the corresponding direction.

Retrieving Filters

You can read from the filters property of a movie clip, button, or text field to retrieve an array of filters already applied to the object. For example, the following retrieves an array of filters already applied to exampleClip:

  var filtersArr:Array = exampleClip.filters;


However, it's important to note that when you read from the filters property it returns an array of copies of the filters already applied to the object. It's an important distinction, and it has several repercussions as you'll read in the next few sections.

Appending Filters

As noted in the preceding section, the filters property returns a copy of the array of filters applied to an object. So if you want to append filters to the list of filters already applied to an object, you cannot go about it in some of the ways you might expect. For example, the following will not work to append a new BevelFilter to exampleClip:

   exampleClip.filters.push(new BevelFilter());


If you want to append a filter to an existing list of filters, you must first retrieve the copy of the array of existing filters.

  var filtersArr:Array = exampleClip.filters;


Then, you can append the new filter to that array.

  filtersArr.push(new BevelFilter());


After the new array contains the correct list of filters, you can assign it to the filters property of the object.

  exampleClip.filters = filtersArr;


Deleting Filters

If you want to delete filters from an object, the same rules apply as when appending. If you want to delete one or more filters, but leave one or more applied, you must retrieve the copy array, modify the copy, and reassign it to the object's filters property.

If you want to delete all the filters applied to an object, you can simply assign null to the filters property.

   exampleClip.filters = null;


Updating Filters

If you want to update a filter applied to an object, you must first retrieve a copy of the filter via the filters property. You can then update the properties of that filter object and then reapply the filter. The following code assumes that exampleClip has a DropShadowFilter instance applied as the first filter in the filters array. It retrieves the current filters array, updates the alpha property of the DropShadowFilter in the first element of the array, and then reassigns the array to the filters property of exampleClip.

   var filtersArr:Array = exampleClip.filters;    filtersArr[0].alpha++;    exampleClip.filters = filtersArr;


Continuing the Spaceship Game

In this task you'll continue building the spaceship game. In this second stage, you'll add a blur to the spaceship when it moves.

1.

Open the Flash document you completed from the previous task. Or optionally open spaceship2.fla from Lesson09/Completed.

The Flash document has the necessary assets as well as the ActionScript code from stage 1. It is the starting point for stage 2.

2.

Select the keyframe on the Actions layer, open the Actions panel, and add the following import statement immediately following the existing import statement:

  import flash.filters.BlurFilter;


In this task you're adding a blur to the spaceship when it moves. That requires the BlurFilter class. To simplify working with the class, import it to start.

3.

Edit the onKeyDown() function by adding a BlurFilter object to the shipClip filters array each time an arrow key is pressed. The updated code is as follows:

   function onKeyDown():Void {      if(Key.getCode() == Key.RIGHT) {        shipClip.filters = bevelArr.concat(new BlurFilter(50));        shipClip.onEnterFrame = function():Void {          this._x += 20;        };      }      else if(Key.getCode() == Key.LEFT) {        shipClip.filters = bevelArr.concat(new BlurFilter(50));        shipClip.onEnterFrame = function():Void {          this._x -= 20;        };      }      else if(Key.getCode() == Key.UP) {        shipClip.filters = bevelArr.concat(new BlurFilter(0, 50));        shipClip.onEnterFrame = function():Void {          this._y -= 20;        };      }      else if(Key.getCode() == Key.DOWN) {        shipClip.filters = bevelArr.concat(new BlurFilter(0, 50));        shipClip.onEnterFrame = function():Void {          this._y += 20;        };      }    }


When the user presses either the right or left arrow keys, the code applies a BlurFilter object to the spaceship with a 50-pixel blur in the x direction. When the user presses either the up or down arrow keys, the code applies a BlurFilter object with a 50-pixel blur in the y direction. The effect is that when the user presses the right or left keys the spaceship appears to have a motion blur applied from right to left, and when the user presses the up or down keys the spaceship appears to have a motion blur applied from top to bottom.

However, notice that the code does not merely apply the blur in place of the bevel. It applies a new array with two elements: the bevel and the blur. The bevelArr array contains the BevelFilter object. The concat() method returns a new array with two elements.

4.

Edit the onKeyUp() function so that it clears the blur filter. The updated function is as follows:

  function onKeyUp():Void {     shipClip.filters = bevelArr;     delete shipClip.onEnterFrame;   }


While the spaceship is moving, you want the blur applied. However, after the spaceship stops you want to remove the blur, which you can accomplish by assigning bevelArr to the filters property of shipClip.

5.

Test the movie.

When you move the spaceship with the arrow keys you ought to see a blur applied in addition to the bevel. When the spaceship stops, the blur is removed, but the bevel remains.

Completing the Spaceship Game

In this next task, you'll complete the spaceship game. In this stage you'll add meteors that animate across the Stage. If a meteor collides with the spaceship, it will deduct 10 points and it will add a glow effect to the spaceship to indicate that it was hit.

1.

Open the completed Flash document from the preceding stage. Optionally, open spaceship3.fla from Lesson09/Completed.

The Flash document has all the assets to complete the game.

2.

Select the Meteor symbol in the library and open the Linkage Properties dialog box. Check the Export For ActionScript option and use the default linkage identifier of Meteor.

The Meteor symbol is used for the meteors that animate across the Stage. Because you'll be adding instance programmatically, you need to set the symbol to export.

3.

Select the keyframe in the Actions layer and open the Actions panel. Add the following import statements immediately following the existing import statements:

    import flash.filters.GlowFilter;     import mx.transitions.Tween;


You'll use the GlowFilter class to add the glow effect to the spaceship. The Tween class is utilized by the meteors. It animates them across the Stage. In both cases, you can import the classes to start to simplify working with them through the code.

4.

Set an interval calling a function called addMeteor() every five seconds. Add the following code immediately following the line of code that registers the listener with the Key class:

   setInterval(this, "addMeteor", 5000);


The setInterval() function tells Flash Player to call a function at a frequency determined in milliseconds. In this case, it's telling Flash Player to call addMeteor() every 5000 milliseconds, or 5 seconds.

5.

Define the addMeteor() function as follows. Place the function just after the onKeyUp() function.

   function addMeteor():Void {      this.attachMovie("Meteor", "meteorClip", this.getNextHighestDepth());      var angle:Number = Math.random() * 2 * Math.PI;      meteorClip._x = Math.cos(angle) * 600 + backgroundClip._x;      meteorClip._y = Math.sin(angle) * 600 + backgroundClip._y;      angle += Math.PI;      new Tween(meteorClip, "_x", null, meteorClip._x, ¬        Math.cos(angle) * 600 + backgroundClip._x, 40);      var meteorTween:Tween = new Tween(meteorClip, "_y", ¬        null, meteorClip._y, Math.sin(angle) * 600 + backgroundClip._y, 40);      meteorTween.addListener(this);    }


The addMeteor() function adds a new instance of the Meteor symbol using the attachMovie() method. It then determines where to place the instance using trigonometry. The trigonometry is required so that each meteor is placed randomly along a circle that is concentric with the middle of the background. Then, using a Tween object, the code animates the meteor to the opposite side of the circle. It registers the main Timeline as the listener object for the Tween object so that it gets notified when the tween has completed.

6.

Define the onMotionFinished() function as follows (add the code after the addMeteor() function):

  function onMotionFinished(tweenInstance:Tween):Void {     tweenInstance.obj.removeMovieClip();     collisionClip = null;   }


The onMotionFinished() gets called each time a meteor completes its animation to the opposite side of the circle. The function removes the movie clip instance. It also sets collisionClip to null. The collisionClip variable is used during collision detection. After the meteor completes moving across the Stage, you want to reset collisionClip.

7.

Set an interval to check for collisions. Add the following code following the setInterval() code from Step 4:

   setInterval(this, "checkCollision", 100);


The game needs to see whether the meteors have collided with the spaceship. To accomplish that, use an interval that calls checkCollision() every 100 milliseconds.

8.

Define checkCollision() as follows (add the code following the onMotionFinished() function):

  function checkCollision():Void {     if(collisionClip == meteorClip) {       return;     }     if(shipClip.hitTest(meteorClip)) {       collisionClip = meteorClip;       shipClip.filters = shipClip.filters.concat(new ¬         GlowFilter(0xFF0000, 50, 20, 20));       setTimeout(this, "resetFilters", 1000);       scoreField.text = parseInt(scoreField.text) - 10;     }   }


The checkCollision() function uses the hitTest() method to see whether shipClip and meteorClip have collided. If so, it appends a GlowFilter instance to the filters array for shipClip. It then uses setTimeout() in order to call resetFilters() in one second. It decrements the score by 10.

You'll also notice that checkCollision() uses collisionClip, the variable defined in an earlier stage. It's possible that checkCollision() could get called more than once during one collision between a meteor and the spaceship. However, you want the collision to get registered just once per meteor. When a collision is detected, collisionClip is assigned a reference to meteorClip. Then, if checkCollision() is called again during the same collision the if statement evaluates to true, and it exits the function. As you saw in Step 6, the collisionClip variable is reset to null after the meteor moves across the Stage.

9.

Define the resetFilters() function as follows. Place the code so it follows the checkCollision() function.

  function resetFilters():Void {     var filtersArr:Array = shipClip.filters;     if(filtersArr[filtersArr.length - 1] instanceof GlowFilter) {       filtersArr.pop();     }     shipClip.filters = filtersArr;   }


The resetFilters() function simply resets the filters applied to the spaceship to whatever they were before the glow was applied.




Macromedia Flash 8 ActionScript Training from the Source
Macromedia Flash 8 ActionScript: Training from the Source
ISBN: 0321336194
EAN: 2147483647
Year: 2007
Pages: 221

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net