Saturday 12 October 2013

History of EventDispatcher in AS3



The EventDispatcher class is the base class for all classes that dispatch events. The EventDispatcher class implements the IEventDispatcher interface and is the base class for the DisplayObject class. The EventDispatcher class allows any object on the display list to be an event target and as such, to use the methods of the IEventDispatcher interface.
Event targets are an important part of the Flash Player and Adobe AIR event model. The event target serves as the focal point for how events flow through the display list hierarchy. When an event such as a mouse click or a keypress occurs, Flash Player or the AIR application dispatches an event object into the event flow from the root of the display list. The event object then makes its way through the display list until it reaches the event target, at which point it begins its return trip through the display list. 

This round-trip journey to the event target is conceptually divided into three phases: 
the capture phase comprises the journey from the root to the last node before the event target's node, 
the target phase comprises only the event target node, and 
the bubbling phase comprises any subsequent nodes encountered on the return trip to the root of the display list.

In general, the easiest way for a user-defined class to gain event dispatching capabilities is to extend EventDispatcher. If this is impossible (that is, if the class is already extending another class), you can instead implement the IEventDispatcher interface, create an EventDispatcher member, and write simple hooks to route calls into the aggregated EventDispatcher.

Public Methods :-

EventDispatcher(target:IEventDispatcher = null)
Aggregates an instance of the EventDispatcher class.

addEventListener(type:String, listener:Function, useCapture:Boolean = false, priority:int = 0, useWeakReference:Boolean = false):void
Registers an event listener object with an EventDispatcher object so that the listener receives notification of an event.

dispatchEvent(event:Event):Boolean
Dispatches an event into the event flow.

hasEventListener(type:String):Boolean
Checks whether the EventDispatcher object has any listeners registered for a specific type of event.

removeEventListener(type:String, listener:Function, useCapture:Boolean = false):void
Removes a listener from the EventDispatcher object.

willTrigger(type:String):Boolean
Checks whether an event listener is registered with this EventDispatcher object or any of its ancestors for the specified event type.


Events :- 

Activate :- Dispatched when the Flash Player or AIR application gains operating system focus and becomes active
Deactivate :- Dispatched when the Flash Player or AIR application operating loses system focus and is becoming inactive.


Sample Code :- 


The following example uses the classes EventDispatcherExample and CustomDispatcher, a subclass of EventDispatcher, to show how a custom event is created and dispatched. The example carries out the following tasks:
The constructor of EventDispatcherExample creates a local variable dispatcher and assigns it to a new CustomDispatcher instance.
Inside CustomDispatcher, a string is set so that the event has the name action, and the doAction() method is declared. When called, this method creates the action event and dispatches it using EventDispatcher.dispatchEvent().
The dispatcher property is then used to add the action event listener and associated subscriber method actionHandler(), which simply prints information about the event when it is dispatched.
The doAction() method is invoked, dispatching the action event.
package {
    import flash.display.Sprite;
    import flash.events.Event;

    public class EventDispatcherExample extends Sprite {

        public function EventDispatcherExample() {
            var dispatcher:CustomDispatcher = new CustomDispatcher();
            dispatcher.addEventListener(CustomDispatcher.ACTION, actionHandler);
            dispatcher.doAction();
        }

        private function actionHandler(event:Event):void {
            trace("actionHandler: " + event);
        }
    }
}




import flash.events.EventDispatcher;
import flash.events.Event;

class CustomDispatcher extends EventDispatcher {
    public static var ACTION:String = "action";

    public function doAction():void {
        dispatchEvent(new Event(CustomDispatcher.ACTION));
    }
}

Download Source code

Friday 11 October 2013

History of timer class in as3

The Timer class is the interface to timers, which let you run code on a specified time sequence. Use the start() method to start a timer. Add an event listener for the timer event to set up code to be run on the timer interval.
You can create Timer objects to run once or repeat at specified intervals to execute code on a schedule. Depending on the SWF file's frame rate or the runtime environment (available memory and other factors), the runtime may dispatch events at slightly offset intervals. For example, if a SWF file is set to play at 10 frames per second (fps), which is 100 millisecond intervals, but your timer is set to fire an event at 80 milliseconds, the event will be dispatched close to the 100 millisecond interval. Memory-intensive scripts may also offset the events.

TimerExample :- 

The following example uses the class TimerExample to show how a listener method timerHandler() can be set to listen for a new TimerEvent to be dispatched. The timer is started when start() is called, and after that point, the timer events are dispatched.

package {
    import flash.utils.Timer;
    import flash.events.TimerEvent;
    import flash.display.Sprite;

    public class TimerExample extends Sprite {

        public function TimerExample() {
            var myTimer:Timer = new Timer(1000, 2);
            myTimer.addEventListener("timer", timerHandler);
            myTimer.start();
        }

        public function timerHandler(event:TimerEvent):void {
            trace("timerHandler: " + event);
        }
    }
}


Public Properties :-

currentCount : int
[read-only] The total number of times the timer has fired since it started at zero.
delay : Number
The delay, in milliseconds, between timer events. 
repeatCount : int
The total number of times the timer is set to run.
running : Boolean
[read-only] The timer's current state; true if the timer is running, otherwise false.




Public Methods :- 

Timer(delay:Number, repeatCount:int = 0)
Constructs a new Timer object with the specified delay and repeatCount states.
reset():void
Stops the timer, if it is running, and sets the currentCount property back to 0, like the reset button of a stopwatch.
start():void
Starts the timer, if it is not already running.
stop():void
Stops the timer.

Events :- 

timer  - Dispatched whenever a Timer object reaches an interval specified according to the Timer.delay property.
timerComplete - Dispatched whenever it has completed the number of requests set by Timer.repeatCount.

currentLabel and currentFrameLabel in as3

This came to me as a surprise as there are two properties of a movieclip for the label of a frame. “currentLabel” and “currentFrameLabel” are those two properties which will give you the label string of a particular frame. There is a very subtle difference in these two.
currentFrameLabel : This gives the string value of the label of the current frame. And this is different for each(lets stress,its different for each) frame unless not defined,in that case it would be null.

currentLabel : This too gives the string value of the label of the current frame. But it is same for the in between frames (the frames between 2 different labels). It returns the label of the current frame if its defined,else it returns the label of the previous frame, else it will return the label of the last to last frame. If there are no labels defined from the beginning, then only it will return null.

Sample Code :-

package
{
            import flash.display.MovieClip;
            import flash.events.Event;
           
            public class UnderstandingLabel extends MovieClip
            {
                        public function UnderstandingLabel():void
                        {
                                    trace(this,' : Constructor : ');
                                    this.init();
                        }
                        private function init():void
                        {
                                    this.addEventListener(Event.ENTER_FRAME,checkOnEachFrame);
                        }
                        private function checkOnEachFrame(e:Event):void
                        {
                                    trace(this,':checkOnEachFrame :: this.currentFrame=',this.currentFrame);
                                    trace(this,':checkOnEachFrame :: this.currentLabel=',this.currentLabel,':: this.currentFrameLabel=',this.currentFrameLabel);
                                    if(this.currentFrameLabel!=null)
                                    {
                                                trace('-----------------------------------------At frame number',this.currentFrame,' this.currentFrameLabel !=null');
                                    }
                                   
                                    if(this.currentFrame>=this.totalFrames)
                                    {
                                                this.removeEventListener(Event.ENTER_FRAME,checkOnEachFrame);
                                    }
                        }
            }

}

The distance between two points or players in as3



package
{

import flash.display.Sprite;

public class testClass extends Sprite
{
var player1:Player1;
var player2:Player2;
var dist:int;
public function testClass()
{
// constructor code
player1_fun();
player2_fun();
playersBetweenDist();
}
public function player1_fun(){
player1 = new Player1();
addChild(player1);
player1.x = 30;
player1.y = 30;

}
public function player2_fun(){
player2 = new Player2();
addChild(player2);
player2.x = 30;
player2.y = 70;
}
public function playersBetweenDist(){
dist = Math.sqrt(Math.pow( player2.x - player1.x,2 ) + Math.pow( player2.y - player1.y,2 ) );

trace("The distance between two players = "+dist);
}

}

}














Note : - You can change player co-ordinates to see the difference between distance

Wednesday 18 September 2013

TypeError: Error #1034: Type Coercion failed: cannot convert the_game@24d270b1 to flash.display.MovieClip

there is nothing wrong with your code.  So since the error is indicating you are trying to treat a MovieClip as if it is a SimpleButton or any , somewhere in your design you have done something to attempt to coerce that MovieClip into being a Button (or possibly vice versa if it is actually a Button).  Check the properties panel and elsewhere to see if you have selected something that would be trying to make that button a different type of object than what it is.


Try creating a new movieclip and assign it that name (removing it from the other) and see if you still get the error.  If that works, then I recommend just creating a new movieclip and replacing it for the current one that is giving you the problem.

1180 error:Call to a possibly undefined method addFrameScript in as3

Sol 1 :-

Let me get this straight: you have set a Document Class in fla properties and are writing code directly in fla as well?
If this is the case, solution is simple: either write your code only in external .as files and not fla or do not use Document Class if you wish continue writing code on the Timeline. The error code you get states that you have code on your Timeline which behaves like a MovieClip, while your Document Class extends Sprite and therefore is not aware of method called addFrameScript (this method is called while compiling code that is on the Timeline into SWF file).
In short, I'd adviced you to change


public class SetTimeoutExample extends Sprite {
to
public class SetTimeoutExample extends MovieClip {

and move all your fla code to Document Class



Sol 2 :-

I solved the problem and now I'm successfully using an external AS class while implementing some other function on the TimeLine:

The problem can be solved just following this simple "rule":

if you want to JUST load everything from the external CLASS, you have to "link" the .fla file to the .as ("Document Class"):

the timeline use the addFrameScript function

if you want to USE something from the class, while doing something else on the timeline, you JUST HAVE TO PUT a similar line on the TimeLine:

var myClassObject:myClass = new myClass();
this.addChild(myClassObject);

Tuesday 17 September 2013

MVC Design Pattern in AS3

“Model-view-controller (MVC) is an architectural pattern used in software engineering. Successful use of the pattern isolates business logic from user interface considerations, resulting in an application where it is easier to modify either the visual appearance of the application or the underlying business rules without affecting the other. In MVC,

The model represents the information (the data) of the application and the business rules used to manipulate the data;
The view corresponds to elements of the user interface such as text, checkbox items, and so forth;
The controller manages details involving the communication to the model of user actions such as keystrokes and mouse movements.”

The MVC Design Pattern
Creates a separation of Class roles
Adds a clear and logical communication structure
Increases flexibility in larger applications
Model
    Handles data storage and retrieval (eg. Store character x position)
View
    Handles the display/communication (eg. Position character on stage)
Controller
    Handles most the of the application logic (eg. Get current x position)

MVC – basic structure
Each model can have multiple views
Each view has at least one matching controller
Creates a separation between form, content and action
The model becomes the base of the application




Sample Game:-

Aim:-

A Square with randomly changed color when button was pressed

Architecture:-


Wednesday 29 May 2013

URL Redirect code in as2 and as3 ( WEB Address / MAIL Address )

AS2 :- 

 Method 1(in button)  :-


on (release) { getURL("http://www.zopy.blogspot.com", '_blank'); }


 Method 2 (in action panel)  :-

zopylogo.onRelease = function(){ getURL("http://www.zopy.blogspot.com", '_blank'); }



AS3 :-


import flash.events.MouseEvent; import flash.net.URLRequest; import flash.net.navigateToURL; zopylogo.addEventListener(MouseEvent.MOUSE_UP, onClick); function onClick(e:MouseEvent):void { var click_url:String = "http://www.zopy.blogspot.com"; if(click_url) { navigateToURL(new URLRequest(click_url), '_blank'); } }


Note :- _blank :- redirects another tab
_self :- redirects same tab




 If you want to link to an email address you use the same code as above in AS 2 and 3 but you replace the object with 'mailto:yourMail@yourEmail.com'.


AS 2
on (release){
    getURL("mailto:yourMail@yourEmail.com");
}


AS 3
var mail:URLRequest = new URLRequest("mailto:yourMail@yourEmail.com");

myButton.addEventListener(MouseEvent.CLICK, goMail);

function goMail(event:MouseEvent):void {
     navigateToURL(mail);
}

Wednesday 27 March 2013

How to embed viemo video in flash using as3




//import com.candybox.simpleshit.VideoXML;
import com.candybox.simpleshit.VimeoPlayer;
//import com.candybox.simpleshit.DrawTile;

Security.allowDomain('*');


var x_player:Number = 0;
var y_player:Number = 0;

var player:VimeoPlayer=new VimeoPlayer("CONSUMER_KEY",47698513,500,400,x_player,y_player,10);
this.addChild(player);


How to import you-tube video on flash using as3

Security.allowDomain("www.youtube.com");

var my_player:Object;

var my_loader:Loader = new Loader();
my_loader.load(new URLRequest("http://www.youtube.com/apiplayer?version=3"));
my_loader.contentLoaderInfo.addEventListener(Event.INIT, onLoaderInit);

function onLoaderInit(e:Event):void{
addChild(my_loader);
my_player = my_loader.content;
my_player.addEventListener("onReady", onPlayerReady);
}

function onPlayerReady(e:Event):void{
my_player.setSize(640,360);
my_player.cueVideoById("XYDCH-vudJk",0);
}

/*play_btn.addEventListener(MouseEvent.CLICK, playVid);
function playVid(e:MouseEvent):void {
my_player.playVideo();
}
pause_btn.addEventListener(MouseEvent.CLICK, pauseVid);
function pauseVid(e:MouseEvent):void {
my_player.pauseVideo();
}*/




Friday 8 March 2013

draw a line using keyboard arrows

Code :-
=====


import flash.events.Event;
graphics.lineStyle(2);
graphics.beginFill(0x00ff00);

stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyPressed);
function onKeyPressed(evt:KeyboardEvent):void
{
switch (evt.keyCode)
{
case Keyboard.UP :
//box= box.y++;
box.y = box.y - 1;
graphics.moveTo(box.x, box.y);
graphics.lineTo(box.x, box.y-1);
trace("up");
break;
case Keyboard.DOWN :
///box= box.y--;
box.y = box.y + 1;
graphics.moveTo(box.x, box.y);
graphics.lineTo(box.x, box.y+1);
trace("down");
break;
case Keyboard.LEFT :
//box= box.x--;
box.x = box.x - 1;
graphics.moveTo(box.x, box.y);
graphics.lineTo(box.x-1, box.y);
trace("left");
break;
case Keyboard.RIGHT :
//box= box.x++;
box.x = box.x + 1;
graphics.moveTo(box.x, box.y);
graphics.lineTo(box.x+1, box.y);
trace("right");
break;
default :
trace("keyCode:", evt.keyCode);
}
}

out put :-
======


full screen code in as3

Code :-
=====


import flash.display.StageDisplayState;
function goFullScreen():void
{
if (stage.displayState == StageDisplayState.NORMAL)
{
stage.displayState = StageDisplayState.FULL_SCREEN;
}
else
{
stage.displayState = StageDisplayState.NORMAL;
}
}
fs_button.addEventListener(MouseEvent.CLICK, _handleClick);
function _handleClick(event:MouseEvent):void
{
goFullScreen();
}

Out Put :-
======
Check output at published swf file.


pendulum movement in as3


Code :-
=====

var startingAngle:Number = 90;
var gravity:Number = 0.1;
var currentForce:Number = 0;
pendulum.rotation = startingAngle;
stage.addEventListener(Event.ENTER_FRAME, loop);
function loop(e:Event):void
{
currentForce -= pendulum.rotation / (gravity * 150);
pendulum.rotation +=  currentForce;
}

rotate a stick continuously in as3


Code :-
=====


stage.addEventListener(Event.ENTER_FRAME,rotate);

function rotate (e:Event){
       var theX:int = 5//mouseX - arrow.x;
       var theY:int = 13//(mouseY - arrow.y) * -1;
       var angle = Math.atan(theY/theX)/(Math.PI/90);
       trace(angle);

     
arrow.rotation -= (angle*-1) + 90
   
}

Out put :-
======



rotate a object z axis


Code :-
=====


var startingAngle:Number = 45;
var gravity:Number = 0.1;
var currentForce:Number = 0;
arrow.rotationX = startingAngle;
stage.addEventListener(Event.ENTER_FRAME, loop);
function loop(e:Event):void
{
currentForce -= arrow.rotationX / (gravity * 1500);
arrow.rotationX +=  currentForce;
}

Out put :-
======



zoom in, out and drag isometric land in as3



Code :-
=====

land.addEventListener(MouseEvent.MOUSE_DOWN,moveland);
land.addEventListener(MouseEvent.MOUSE_UP,releaseland);
land.buttonMode = true;
function moveland(event:Event):void
{
event.target.startDrag();

}
function releaseland(event:Event):void
{
event.target.stopDrag();

}
import fl.transitions.*;
import fl.transitions.easing.*;
import fl.motion.easing.*;
var factorZoom:Number;


stage.addEventListener(MouseEvent.MOUSE_WHEEL ,onclick);
factorZoom=1;
function onclick(e:MouseEvent) {
if (e.delta>0) {
factorZoom=factorZoom+0.01;
trace(factorZoom);
} else if (e.delta<0) {
factorZoom=factorZoom-0.01;
}
imageToZoom();
}


function imageToZoom():void {
var overPixelX:Number=land.mouseX;
var overPixelY:Number=land.mouseY;
//
land.scaleX=land.scaleY=factorZoom;
var pixelDifferenceX:Number = (overPixelX - land.mouseX) * factorZoom;
var pixelDifferenceY:Number = (overPixelY - land.mouseY) * factorZoom;
//
var nextX:Number=land.x-pixelDifferenceX;
land.x=checkNewX(nextX);
//
var nextY:Number=land.y-pixelDifferenceY;
land.y=checkNewY(nextY);
}

function checkNewY(checkY:Number):Number {
if (land.height<600) {
return (600 - land.height) / 2;
}
if (checkY>0) {
checkY=0;
} else if (checkY + land.height < 600) {
checkY=600-land.height;
}
return checkY;
}
function checkNewX(checkX:Number):Number {
if (land.width<800) {
return (800 - land.width) / 2;
}
if (checkX>0) {
checkX=0;
} else if (checkX + land.width < 800) {
checkX=800-land.width;
}
return checkX;
}

Out Put :-
=======


create dynamic movieclip, import external images and mouse down listener in as3


Code :-
=====

var mc_clips:Array=[];
var aalage_bigloader:Array=[];

for (var i:Number = 1; i < 3; i++) {
var mc:MovieClip = new MovieClip();
mc.name="alage_big"+i;
mc_clips[i]=mc;

for (var j:Number = 1; j < 3; j++) {
var alage_bigloader = new Loader();
alage_bigloader.name="alage_bigloader"+j;
aalage_bigloader[j]=alage_bigloader;
}
addChild(mc_clips[i]);
aalage_bigloader[1].load(new URLRequest("a.PNG"));
aalage_bigloader[2].load(new URLRequest("b.PNG"));
mc_clips[i].addChild(aalage_bigloader[i]);
}
mc_clips[1].x=13;
mc_clips[1].y=82;
mc_clips[2].x=130;
mc_clips[2].y=100;

mc_clips[1].addEventListener(MouseEvent.MOUSE_DOWN,click_fun);
function click_fun(e:MouseEvent) {
trace("111111111111111111111");
}
mc_clips[2].addEventListener(MouseEvent.MOUSE_DOWN,click2_fun);
function click2_fun(e:MouseEvent) {
trace("2222222222222222222222222");
}

Out put :-
=======






How to receive data through xml in as3


Code :-
=====


var XMLreceive:URLRequest = new URLRequest("XML.xml");
var XMLreceiveLoader:URLLoader = new URLLoader(XMLreceive);
XMLreceiveLoader.addEventListener("complete",XMLreceivefun1);

function XMLreceivefun1(event:Event):void
{

var XMLDoc:XMLDocument = new XMLDocument();
XMLDoc.ignoreWhite = true;
var XMLreceive1:XML = XML(XMLreceiveLoader.data);
XMLDoc.parseXML(XMLreceive1.toXMLString());

trace(XMLDoc.firstChild.childNodes[0].childNodes[0].childNodes[0]);
//trace(XMLDoc.firstChild.childNodes[0].childNodes[1].childNodes[0]);

}

Out put :-
=======
63

File Structure :-  ( For send and receive )
===========


How to send data through xml in as3



Code :-
=====

var respTxt:TextField = new TextField();
var myTextFormat:TextFormat = new TextFormat();
myTextFormat.size = 14;

var xmlString:String = "<?xml version='1.0' encoding='ISO-8859-1'?><root><value>63</value></root>";
var book:XML = new XML(xmlString);

var xmlResponse:XML;

var xmlURLReq:URLRequest = new URLRequest("processPHP.php");
xmlURLReq.data = book;
xmlURLReq.contentType = "text/xml";
xmlURLReq.method = URLRequestMethod.POST;

var xmlSendLoad:URLLoader = new URLLoader();
//xmlSendLoad.addEventListener(Event.COMPLETE, onComplete, false, 0, true);
//xmlSendLoad.addEventListener(IOErrorEvent.IO_ERROR, onIOError, false, 0, true);
xmlSendLoad.load(xmlURLReq);

function onComplete(evt:Event):void {
    try {
        xmlResponse = new XML(evt.target.data);
        respTxt.text = xmlResponse;
        removeEventListener(Event.COMPLETE, onComplete);
        removeEventListener(IOErrorEvent.IO_ERROR, onIOError);
    } catch (err:TypeError) {
        respTxt.text = "An error occured when communicating with server:\n" + err.message;
    }
    placeText();
}

function onIOError(evt:IOErrorEvent):void {
    respTxt.text = "An error occurred when attempting to load the XML.\n" + evt.text;
    placeText();
}

function placeText():void {
    respTxt.x = 15;
    respTxt.y = 15;
    respTxt.multiline = true;
    respTxt.autoSize = TextFieldAutoSize.LEFT;
    respTxt.setTextFormat(myTextFormat);
    addChild(respTxt);
}


processPHP.php :-
=============


<?php
$file = fopen("docq.xml", "w+") or die("Can't open XML file");

$xmlString = $HTTP_RAW_POST_DATA;

if(!fwrite($file, $xmlString))
{
    print "Error writing to XML-file";
}
print $xmlString."\n";

fclose($file);

?>


Out put XML  :-
===========


<root>
  <value>63</value>
</root>





How to load external image in as3




Code :-

var salads_btn:MovieClip = new MovieClip();
addChild(salads_btn);

salads_btn.x = 100;
salads_btn.y = 100;

var salads_btn_loader = new Loader();
salads_btn_loader.load(new URLRequest("coffeeitems1.GIF"));
salads_btn.addChild(salads_btn_loader);

Out put :-