Sunday, 25 January 2015

random function in as3

function randomRange(minNum:Number, maxNum:Number):Number
{
    return (Math.floor(Math.random() * (maxNum - minNum + 1)) + minNum);
}

trace(randomRange(1, 6));

out put :-


Monday, 21 July 2014

as2 preloader

stop();
this.onEnterFrame = function()
{
            filesize = _root.getBytesTotal();
            loaded = _root.getBytesLoaded();
            Bar._visible = true;
            if (loaded != filesize)
            {
                        Bar._xscale = 100*loaded/filesize;
            }
            else
            {
delete this.onEnterFrame;
                        gotoAndStop(2);
            }
};

as3-preloader classes

import flash.events.ProgressEvent;
stop();

// progress event
loaderInfo.addEventListener(ProgressEvent.PROGRESS, loadingProgress);
loaderInfo.addEventListener( Event.COMPLETE , finishedLoading );

// simple preloader;
function loadingProgress(e:ProgressEvent):void
{
preloaderBar.scaleX = loaderInfo.bytesLoaded / loaderInfo.bytesTotal;
}
function finishedLoading( evt:Event ):void
{
loaderInfo.removeEventListener( Event.COMPLETE , finishedLoading );
gotoAndStop(2);
}


// if you are using classes code you can use ProgressEvent in timeline and use  Event.COMPLETE in classes ( Main.as )
But you have to remember several thing .....

1. you should load your pre-loader animation in frame 1
2. Should change Advanced ActionScript Settings => Export Classes in frames 2 ( frame 2)

Check below fig. for more info.......




















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