Saturday, January 29, 2011

Tweening: Part - I

Tweening word is the formation from the words "in between". As suggested by the meaning, tweening has something to do with whatever motion is happening "in between" 2 states. For example, a ball drops from 10th floor of a building to the ground. So here, whatever motion the ball has "in between" the 10th floor and the ground constitutes the tweening effect.

We can make use of the tweening effect in 2 ways:

1. Using time lines
2. Using code / action script

To add the tween motion using the timeline, add the first state of the object in the first frame. The state could be any property, like, color, dimensions, x-y co-ordinates etc. Leave 18 frames in between, and add a key frame to the 20th frame. Add second state of the same object (change any of the above mentioned properties). Right click on the timeline anywhere between the first and the 20th frame. There will be an option to add tween effect. Select that, and you will find the the tween motion is added to your timeline. Press enter while in the first frame, you will see how the tween effect comes out in the time line.

Tweening can be added using action script as well. The tween class is not included in the flash movie by default. It needs to be imported as follows:

import fl.transitions.Tween;
import fl.transitions.easing.*;


Tween class is to add tween motion to the desired object. Lets check what does "easing" do. "Easing" refers to gradual acceleration or deceleration during an animation, which helps your animations appear more realistic. The fl.transitions.easing package provides many easing methods that contain equations for this acceleration and deceleration, which change the easing animation accordingly.

Another class TweenEvent can be imported as follows (though not mandatory)

import fl.transitions.TweenEvent;

This class besically contains a few events, like, MOTION_CHANGE, MOTION-FINISH, MOTION_START, etc etc. Such events can be fired to handle any other changes as per the requirements. This will be explained in the next post.

Now let us see how tweening class is used. Check out the syntax below:

var myTween:Tween = new Tween(object, "property", EasingType, begin, end, duration, useSeconds);

The parameters mentioned above are mandatory to be specified whenever the Tween class is instantiated. Each of them is explained as follows:

  1. object - This is the instance name of the object which will be animated or on which tween is applied. Example: myMovie, myTxt
  2. property - This is the name of the property which will be animated, it must be specified as a string (in double quotes). Example: "alpha", "scaleX", "scaleY", "x", "y".
  3. EasingType - The easing type will determine how the tween animation will flow so that it looks natural and real. Examples: Strong.EaseIn, Elastic.EaseOut, Back.EaseInOut.
  4. begin - This is the position from which the animation will start, it must be specified as a number.
  5. end - This is the position at which the animation will stop, it must be specified at as a number.
  6. duration - This is the period for which the animation will run, the default unit for it is frames, however, the unit can be set in seconds if you set the next parameter as true.
  7. useSeconds - Set this parameter to true if you want to the duration to be measured in seconds instead of frames
For example:

var myTween:Tween = new Tween(myMovie, "x", Strong.easeOut, 25, 100, 10, true);

In the above script, observe the third parameter, Strong.easeOut. This is a function which has a property easeOut. Like "Strong" we have 5 more functions, each of them described as follows:
  1. Regular: the motion speed will gradually increase or decrease in speed as specified by the easing method.
  2. Bounce: the motion will bounce back a few steps when it reaches the end position before settling at it.
  3. Back: the motion will go beyond the end position before bouncing back into it.
  4. Elastic: a mixture of Bounce and Back effects combined.
  5. Strong: a more emphasized Regular effect.
  6. None: no easing, the motion will not speed up.
Each of these functions must be then be configured using one of the easing methods to determine at which part of the tween it shall apply the effect, i.e. at the start of it, the end of it, both, or none:
  1. easeIn: - The tween effect is applied to the start of the animation.
  2. easeOut: - The tween effect is applied to the end of the animation.
  3. easeInOut: - the tween effect is applied to the start and end of the animation.
  4. easeNone: - no tweening effect is applied, to be used with the None tween function.

Sunday, January 23, 2011

Creating your own Flash Preloader

We see preloaders in many flash applications these days. An animation, a video, or a movie, or even a game, start mostly with a preloader now. Once the preloader is shown, only then the actual animation starts playing.

What is a Preloader ?

A preloader is a horizontal bar that keeps scaling up and the intensity of the scale depends on the loaded bytes of the file. When the files are loaded completely, the bar reaches its maximum length. The intensity of the bar load-scale is calculated as per the following formula:

                          load-scale = (bytes loaded) / (total no of bytes)

How to create a simple Preloader ?

Step 1: Create a horizontal bar, and convert it into a movie clip.


Step 2: Give an instance name, say, loadMC.



Step 3: Create a dynamic text field, in the same layer (though not mandatory).



Step 4: Give instance name to this text field as well, say, loadTxt



Step 5: Create another layer for the code / script.



Step 6: Put a stop( ) to the first frame, and then add an event listener, ENTER_FRAME, so that the code is executed as soon as the first frame is encountered, and because there is no other frame, the code would keep on executing. Then the files-load percentage is calculated by the above formula, which is displayed in the dynamic text field.



Step 7: Once this is done, press Ctrl+enter. You will get the swf file, displaying the complete horizontal bar and displaying "100%" text below it. Now press Ctrl+enter again, and then the actual preloader function is observed. If not, then go to the "view" options in the swf window and select the download speed according to your requirements and convinience.

Wednesday, January 19, 2011

Capturing Events in Flash : Part III - Creating Custom Events

The way we use the in-built events in action script, similarly we can create our own events and handle them at our own requirements. The only extra thing that needs to be done is the creation of class which will hold our user-defined or custom events.

However, there are few things to be noted in case of custom events. For the in-built event handling, we have a class called "clone( )". As by the name, its clear that it is something to do with a "copy". Basically, clone( ) function creates a copy of the event instance with all the properties associated to it. This is handled implicitly for the pre-defined events. But for the custom events, we need to override this function to our custom event class. This will help duplicate the custom event instance with all the custom properties associated to it.

Why do we need clone( ) function ?

With clone( ) function, the new event object includes all the properties of the original event. Hence, if the event is re-dispatched, then it takes the properties of the already dispatched same event. If you do not set all the properties that you add in your event subclass, those properties will not have the correct values when listeners handle the re-dispatched event.

We can pass arguments as well to these custom events, which also should be cloned.

Another function that needs to be written explicitly for a custom event class is "toString( )". It returns a string containing all the properties of the current instance. This is also to be overridden in the custom event class.
  
Now, let us assume we want to dispatch an event on completion of some animation, event name say "ANIMATION_COMPLETE". We will add an event listener to the movie clip, and will dispatch the event from the last frame, after which the event is handled accordingly.

Check out the code sample below:

package 
{  
         import flash.events.Event;  

         public class CustomEventDemo extends Event  
         {  
                    public var customProperty:String = "";   

                    public var customArgs:*;

                    public static const ANIMATION_COMPLETE:String = "AnimationComplete";
 
                    public function CustomEventDemo(custom:String, custArg:*=null, type:String, bubbles:Boolean = false, cancelable:Boolean = false)  
                   {  
                                // call the constructor of the extended class  
                                 super(type, bubbles, cancelable);  
 
                                // set the customProperty property  
                                customProperty = custom;   


                                // set the customArgs arguments
                                customArgs = custArg;
                   }   


                   public function get args():*
                   {
                                return customArgs;
                   }
 
                   override public function clone():Event  
                   {  
                                return new CustomEventDemo(customProperty, args, type, bubbles, cancelable);  
                   }   


                   override public function toString():String
                   {
                                return formatToString("CustomEventDemo", "args", "type", "bubbles", "cancelable", "eventPhase");
                   }
 
         }  
 
}

Wednesday, January 12, 2011

Implementing MVC Architecture in AS3

MVC stands for Model View Controller. Each of these is an important component for any game development. Their roles are explained as follows:

1.Model: It manages the behavior of any application. It tells how the complete data is structured. It responds to any request made about the game state, mostly by the view.
2.View: It is the display of the information or data to the user.
3.Controller: It interprets the inputs from the user, informs the model to change it, making the view to display the changes accordingly.

In short, the Controller interprets the input, processes it in the Model, and gives the output to the View.


                                                  Input --> Processing --> Output
                                                  Controller --> Model --> View





Take an simple example of a calculator. Calculator is an electronic device that we use in our day to day life. Suppose we want to perform addition operation of 2 numbers. Let us see how the MVC architecture applies here.

First Number Input --> Press the number key of the View --> Input goes to the controller --> controller updates it in model --> the pressed number key is displayed by the view
Operation Input --> Press the "+" key of the View --> Input captured by the controller --> controller updates the model
Second Number Input --> Press the number key of the View --> Input goes to the controller, addition operation is performed --> controller updates the second input and the final output in the model --> the pressed number key is displayed by the view
Result --> Press the "=" key of the View --> Input captured by the controller --> view displays the result as stored in the model

With an MVC architecture, it becomes very easy to write the code in an organized way, and it can then be easily understood by the others as well.

Using MVC in AS3 programming.
Again taking a simple example, capturing data on pressing the keys from the keyboard and priting it in view.

Model will store the data (pressed key) and will be used to retrieve the same.
Hence this will have 2 functions (setter and getter). Model Interface, IModel.as, is written as follows:
package
{
         import flash.events.*;
         public interface IModel
        {
                  function setKeyId(key:uint):void
                  function getKeyId( ):uint
         }
}

The Model.as file becomes:

package
{
         import flash.events.*;
         public class Model implements IModel
        {
                 private var lastKeyId:uint = 0;
                 public function setKeyId(key:uint):void
                {
                         this.lastKeyId = key;
                         dispatchEvent(new Event(Event.CHANGE)); // dispatch event
                }

                 public function getKeyId( ):uint
                {
                         return lastKeyId;
                }
        }
}

All the keyboard events are handled in the Controller. Controller Interface will have just one function to capture the keyboard event:

package
{
         import flash.events.*;
         public interface IController
        {
                  function keyPressHandler(event:KeyboardEvent):void
        }
}

The Controller.as files implements the IController interface:

package
{
         import flash.events.*;
         public class Controller implements IController
        {
                  private var model:IModel;
                  public function Controller(aModel:IModel)
                  {
                             this.model = aModel;
                  }
                 
                 public function keyPressHandler(event:KeyboardEvent):void
                 {
                             model.setKeyId(event.charCode); // change model
                 }
        }
}

The View.as file provides the view to the user, wherein he selects the keyboard key to be pressed, and when the key is presses, View class is useful again to print the key id on the screen.

package
{
         import flash.events.*;
         import flash.display.*;

         public class View
         {
                  private var model:IModel;
                  private var controller:IController;
                  public function View(aModel:IModel, oController:IController,target:Stage)
                  {
                            this.model = aModel;
                            this.controller = oController;

                            // register to receive notifications from the model
                            model.addEventListener(Event.CHANGE, this.update);

                            // register to receive key press notifications from the stage
                            target.addEventListener(KeyboardEvent.KEY_DOWN, this.onKeyPress);

                   }

                  private function update(event:Event):void
                  {
                           // get data from model and update view
                           trace(model.getKeyId( ));
                  }

                  private function onKeyPress(event:KeyboardEvent):void
                  {
                          // delegate to the controller (strategy) to handle it
                          controller.keyPressHandler(event);
                   }
          }
}

And finally, the MainClass.as, where all the class instance are created is :

package
{
         import flash.display.*;
         import flash.events.*;
         public class Main extends Sprite
         {
                  public function Main( )
                  {
                           var model:IModel = new Model( );
                           var controller:IController = new Controller(model);
                           var view:View = new View(model, controller, this.stage);
                  }
         }
}

Let us examine how this complete MVC program work.

MainClass.as class creates the instances of the model, view and the controller classes, which implement the functions of their respective interfaces. The keyboard keys are in the user's view. So, if any key is presses, the event is captured in view and handled in the controller class. The controller updates the model about the key pressed. After which the model dispatches CHANGE event, which signifies that keyboard captured value has been changed (with respect to the previous pressed key value). This event is handled in the view and the keyboard value is displayed to the user on his screen.

References: http://wwwimages.adobe.com/www.adobe.com/content/dam/Adobe/en/devnet/actionscript/pdfs/ora_as3_design_patterns_ch12.pdf

Tuesday, January 11, 2011

Capturing Events in Flash : Part II - Creating Event Handlers

We have already seen few common event classes, let us now try to create a handler for them.
Let us suppose, we have a movieclip, simpleBtn (already present in the respective fla file), we will add a mouse event to it.

this.simplBtn.addEventListener(MouseEvent.CLICK, onClick, false, 0, true);

If you would observe, "addEventListener" takes 5 arguments.

Argument 1: The type of event to capture (in this case its the mouse click event)
Argument 2: The follow up function on dispatching the mouse click event (in this case it is onClick)

The first two arguments are mandatory to be written, whereas the third, fourth, and fifth are optional.

Argument 3: It determines whether the listener works in the capture phase or the target and bubbling phases. If it is set to true, the listener processes the event only during the capture phase and not in the target or bubbling phase. If it is false, the listener processes the event only during the target or bubbling phase.
Argument 4: It is an integer that sets the priority of the listener. Because a single object can use multiple listeners for the same event, it is sometimes useful to specify the order in which the similar listeners are executed. The default value for the priority parameter is 0
Argument 5: It determines whether the reference to the listener is strong or weak. A strong reference (the default as "false") prevents your listener from being garbage-collected. A weak reference does not.

Adding arguments to the function called, when the event is dispatched:

Suppose we want to display a text at simpleTxt, the value of which is passed inside the event listener:

                 this.simplBtn.addEventListener(MouseEvent.CLICK,
                           function(e : MouseEvent) : void
                          {
                                    onClick(e, "button clicked!")
                          },
               false , 0 , false);


               function onClick(e : MouseEvent, str:String) : void
               {
                          this.simpleTxt.text = str;
               }


Hence, the complete code for creating a simple event handler, can be written as follows:

package com{   

           import flash.events.MouseEvent;  

           public class CreatingEventHandler extends Event  
           {      
                      public function CreatingEventHandler()
                      {
                                  init();
                      }


                     private function init():void
                     {
                                  this.simplBtn.addEventListener(MouseEvent.CLICK,
                                  function(e : MouseEvent) : void
                                  {
                                               onClick(e, "button clicked!")
                                  },
                                  false , 0 , false);
                      }


                      private function onClick(e : MouseEvent, str:String) : void
                      {
                                  this.simpleTxt.text = str;
                      }
          }
}

Monday, January 10, 2011

Capturing Events in Flash : Part I - In-Built Events

What is an Event?An event is any specific change/occurrence while the flash application is running. This event can be a caused by any external device, or by completion of a particular step internally by the movie. Following are few in-built event classes in AS3

1.  Event
2.  KeyboardEvent
3.  MouseEvent


Every event has a target associated with it, such that the event occurs on any change done to that particular target.

For example, if we click any button, then that button is the target of that MouseEevent.

Further, every target has a type and name associated with it.

The event target type can be captured as any Button, Movieclip or any other object.
The event target name is the name of the object instance as given in the "fla".

AS3 library provides many in-built events. It is difficult to cover them all in one-go, so let us check the most important ones, that we use in our day-to-day applications.

Mouse Events: Available at flash.events.MouseEvent
10 different operations can be done using the mouse, namely:

1.  CLICK --> associated with any mouse click (down + up) on any object
2.  DOUBLE_CLICK --> associated with any double mouse click (down + up) on any object
3.  MOUSE_DOWN --> associated with any mouse click (down) on any object
4.  MOUSE_MOVE --> associated with any mouse move on any object
5.  MOUSE_OUT --> associated with any mouse out (away from) on any object
6.  MOUSE_OVER --> associated with any mouse kept over on any object
7.  MOUSE_UP --> associated with any mouse click (down + up) on any object
8.  MOUSE_WHEEL --> associated with any mouse scroll on any object
9.  ROLL_OUT --> associated with any mouse out on any particular child of an object
10. ROLL_OVER --> associated with any mouse over on any particular child of an object

KeyBoard Events: Available at flash.events.KeyboardEvent
2 different operations can be done using the keyboard, namely:

1.  KEY_UP --> associated with the released pressed key.
2.  KEY_DOWN --> associated with the pressed key.

Other Events: Available at flash.events.Event
Commonly used events are as follows:
1.  ACTIVATE --> Dispatched when Flash Player or application gains operating system focus and becomes active
2.  ADDED --> Dispatched when the listening displayobject is added to another display object (whether or not in placed in stage
3.  ADDED_TO_STAGE --> Dispatched when the listening displayobject is added to the stage (timeline)
4.  CANCEL --> Dispatched when a file upload or download is canceled through the file-browsing dialog box by the user
5.  CHANGE --> Dispatched when children of any object deal with updating themselves
6.  CLOSE --> Dispatched when the socket connection is closed
7.  COMPLETE --> Dispatched when swf data has loaded successfully
8.  CONNECT --> Dispatched when the socket connection is established
9.  DEACTIVATE --> Dispatched when Flash Player loses operating system focus and is becoming inactive.
10. ENTER_FRAME --> Dispatched every time the playhead enters a new frame and is tied to the frame rate being run by the Flash Player
11. FULLSCREEN --> Dispatched when full-screen mode is turned on or off
12. ID3 --> Dispatched by a Sound object when ID3 data is available for an MP3 sound
13. INIT --> Dispatched when the properties and methods of a loaded SWF file are accessible
14. MOUSE_LEAVE --> Dispatched if you release the mouse button outside the stage
15. OPEN --> Dispatched when an upload or download operation starts
16. REMOVED --> Dispatched whenever a display object is removed from the display list
17. REMOVED_FROM_STAGE --> Dispatched whenever a display object is removed from the stage
18. RENDER --> Dispatched just before the screen is rendered, giving all listening objects the chance to update
19. RESIZE --> Dispatched when the flash window is re-sized, and the parent object handles the re-sizing of all its children
20. SCROLL --> Dispatched whenever any area/field is scrolled (mostly used with text areas)
21. SELECT --> Dispatched when the user selects one or more files to upload from the file-browsing dialog box
22. SOUND_COMPLETE -->Dispatched when the sound finishes playing
23. TAB_CHILDREN_CHANGE --> Dispatched when the value of the object's tabChildren flag changes
24. TAB_ENABLED_CHANGE --> Dispatched when the object's tabEnabled flag changes
25. TAB_INDEX_CHANGE --> Dispatched when the value of the object's tabIndex property changes
26. UNLOAD --> Dispatched when any movie is unloaded

Monday, January 3, 2011

Playing With Colors!

We have studied about colors in the 10th standard physics. There are 3 basic or primary colors, Red(R), Green(G),  Blue(B). Any other color, or a secondary color, is just a combination of these colors, taking single, any two or all three at a time. We have a few common color formations as follows:

R+G ==> Yellow
G+B ==> Cyan
B+R ==> Magenta
R+G+B ==> White

In a rainbow, out of the 7 colors, 3 are primary, and the rest are secondary. Any colored thing that we see, has its own RGB component, and its color visibility depends on the intensity of each component.

Like, if we observe any image by enlarging it, we would find numerous pixels. Apparently, an image is the result of pixel-clustering. Every pixel has it's own RGB component, which provides a color to that pixel. That is how we see the image in various colors.

Flash provides a good option to change the color of any object both at the time of compilation, as well as run-time. Changing the object color at compile-time can be done by using the Flash CS3/ CS4, the same way we do it in Microsoft-Paint. For run time color effects, we have "ColorMatrixFilter", an in-built class in AS3. The constructor of this class takes an array as its argument. The array has 20 elements in it for a 4X5 color transform.

The first five elements of the array are worked upon to calculate the "Red Result" of the pixel, next 5 gives the "Green Result", then next 5 gives the "Blue Result" and finally, the last 5 give the "Alpha Result" of the object. For instance:

Let the array be:
a = [1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0];

or

a = [1,0,0,0,0, 0,1,0,0,0, 0,0,1,0,0, 0,0,0,1,0];

or

a = [1,0,0,0,0,   /* Red */
     0,1,0,0,0,   /* Green */
     0,0,1,0,0,   /* Blue */
     0,0,0,1,0];  /* Alpha Transparency */

All the above 3 notations of color matrix are the same. For each color value in the array, a value of 1 is equal to 100% value being sent to the output.

If sR, sG, sB, sA are the respective red, green, blue and alpha components of each pixel, then "Red Result", "Green Result", "Blue Result" and "Alpha Result" are calculated as follows:

redResult   = (a[0]  * sR) + (a[1]  * sG) + (a[2]  * sB) + (a[3]  * sA) + a[4]
greenResult = (a[5]  * sR) + (a[6]  * sG) + (a[7]  * sB) + (a[8]  * sA) + a[9]
blueResult  = (a[10] * sR) + (a[11] * sG) + (a[12] * sB) + (a[13] * sA) + a[14]
alphaResult = (a[15] * sR) + (a[16] * sG) + (a[17] * sB) + (a[18] * sA) + a[19]

All the 4th elements of each row in the above matrix, can have values between 0.0 to 1.0 (0.0 for no visibility and 1.0 for maximum visibility).

a[4], a[9], a[14] and a[19] are the offset values. As we already know, that any color-effect has a range of 0-255 (0 gives no color effect and 255 gives maximum color effect), so an offset, between -255 and 255, can optionally be added to each result.

Adding more fun to the matrix:

Suppose, we want all the green values in the pixels, to show the red color effect, the resultant matrix would be of like:

a = [1,0,0,0,0,   /* Red */
     1,0,0,0,0,   /* Green */
     0,0,1,0,0,   /* Blue */
     0,0,0,1,0];  /* Alpha Transparency */

The brightness of the image is increased on adding the offset value between 0 to 255, and can be decreased the same way by using offset values between -255 to 0. For example:

Matrix for a more bright image:
[1,0,0,0,25,  /* Red */
 0,1,0,0,25,   /* Green */
 0,0,1,0,25,   /* Blue */
 0,0,0,1,0 ]; /* Alpha Transparency */

Matrix for a less bright image:

[1,0,0,0,-25,  /* Red */
 0,1,0,0,-25,   /* Green */
 0,0,1,0,-25,   /* Blue */
 0,0,0,1,0 ]; /* Alpha Transparency */

Like this, we can give multiple color and brightness effects to any image or object.