Friday 21 December 2012

character random movement on stage as3

var iswalking = false;
var goX = char.x;
var goY = char.y;
var movespeed = 1;
var dir = "down";
var previousDistance:Number = 0;
var currentDistance:Number = 0;
var totalDistance:Number;

goX = Math.floor(Math.random() * (1+ (stage.stageWidth + char.width) + char.width) - char.width);
goY = Math.floor(Math.random() * (1+ (stage.stageHeight + char.height) + char.height) - char.height);

stage.addEventListener(Event.ENTER_FRAME, loop);
function loop(Event)
{// animation handling

    var GetDistance = Math.sqrt(Math.pow(char.x - this.goX,2) + Math.pow(char.y - this.goY,2));
    trace(GetDistance);


    if (iswalking == true)
    {
        char.w.play();
    }
    else
    {
        char.w.gotoAndStop(1);
    }
    // direction handling;
    char.gotoAndStop(dir);
    // movement handling;
    if ((goY-movespeed)>char.y)
    {
        char.y +=  movespeed;
        dir = "down";
        iswalking = true;
    }
    else if ((goY+movespeed)<char.y)
    {
        char.y -=  movespeed;
        dir = "up";
        iswalking = true;
    }
    else if ((goX-movespeed)>char.x)
    {
        char.x +=  movespeed;
        dir = "right";
        iswalking = true;
    }
    else if ((goX+movespeed)<char.x)
    {
        char.x -=  movespeed;
        dir = "left";
        iswalking = true;
    }
    else
    {
        iswalking = false;
        goX = Math.floor(Math.random() * (1+ (stage.stageWidth + char.width) + char.width) - char.width);
        goY = Math.floor(Math.random() * (1+ (stage.stageHeight + char.height) + char.height) - char.height);

    }
}

How to change registration point dynamically as3

function setRegPoint(obj:DisplayObjectContainer, newX:Number, newY:Number):void {
    //get the bounds of the object and the location
    //of the current registration point in relation
    //to the upper left corner of the graphical content
    //note: this is a PSEUDO currentRegX and currentRegY, as the
    //registration point of a display object is ALWAYS (0, 0):
    var bounds:Rectangle = obj.getBounds(obj.parent);
    var currentRegX:Number = obj.x - bounds.left;
    var currentRegY:Number = obj.y - bounds.top;
   
    var xOffset:Number = newX - currentRegX;
    var yOffset:Number = newY - currentRegY;
    //shift the object to its new location--
    //this will put it back in the same position
    //where it started (that is, VISUALLY anyway):
    obj.x += xOffset;
    obj.y += yOffset;
   
    //shift all the children the same amount,
    //but in the opposite direction
    for(var i:int = 0; i < obj.numChildren; i++) {
        obj.getChildAt(i).x -= xOffset;
        obj.getChildAt(i).y -= yOffset;
    }
}
book.addEventListener(MouseEvent.CLICK, bookClicked);
function bookClicked(event:MouseEvent):void {
    book.scaleX += .1;
    book.scaleY += .1;
}

//set the registration point for the book object in the middle instead:
setRegPoint(book, book.width / 2, book.height / 2);

Timer in as3



Timer in AS3:-

  • 1.      Create one dynamic text named as ‘timer’.
  • 2.      Go to action layer and write action script code.
  • 3.      i.e., create one integer variable ‘timer’ assigned as 10.
  • 4.      Create one timer object called ‘MyTimer’. And start the object by using start() function
  • 5.      Create one enterframe event  and format time function for (mm:ss)
  • 6.      And send that format to dynamic text by using .currentCount
  • 7.      Press Ctrl+Enter to check the output.
  •  

var square:MovieClip = new MovieClip();
var loader_txt:TextField = new TextField();
addChild(loader_txt);
addChild(square);

//square.graphics.lineStyle(3,0x00ff00);
square.graphics.beginFill(0x0000FF);
square.graphics.drawRect(0,0,150,15);
square.graphics.endFill();
square.x = stage.stageWidth/2-square.width/2;
square.y = stage.stageHeight/2-square.height/2;

var myTimer:Timer=new Timer(1000,10);
this.addEventListener(Event.ENTER_FRAME, loading);
myTimer.start();
function loading(e:Event):void {
    var total:Number=5;
    var loaded:Number=myTimer.currentCount;
    square.scaleX=loaded/total;
    loader_txt.text = ((loaded/total)*100)+ "%";
    if (total==loaded) {
        play();
        this.removeEventListener(Event.ENTER_FRAME, loading);
    }

}




var myTimer:Timer=new Timer(1000,10);
this.addEventListener(Event.ENTER_FRAME, loading);
myTimer.start();
function loading(e:Event):void {
    var total:Number=10;
    var loaded:Number=myTimer.currentCount;
    bar_mc.scaleX=loaded/total;
    loader_txt.text = ((loaded/total)*100)+ "%";
    if (total==loaded) {
        play();
        this.removeEventListener(Event.ENTER_FRAME, loading);
    }

}



zoom in, zoom out in as3




var count_zoom:Number = 0;

zoomInButton.addEventListener(MouseEvent.MOUSE_DOWN, zoomIn);
zoomOutButton.addEventListener(MouseEvent.MOUSE_DOWN, zoomOut);
function zoomIn(e:MouseEvent)
{
    bg.scaleX +=  .1;
    bg.scaleY +=  .1;
    count_zoom++;

}
function zoomOut(e:MouseEvent)
{
    bg.scaleX -=  .1;
    bg.scaleY -=  .1;
    count_zoom--;

}


stage.addEventListener(Event.ENTER_FRAME, loop);
function loop(e:Event)
{
    if (count_zoom == 0)
    {
        trace("0");
        zoomOutButton.visible = false;
    }
    if (count_zoom == 5)
    {
        trace("5");
        zoomInButton.visible = false;
    }
    if (count_zoom >= 1 && count_zoom <= 4)
    {
        trace("1,2,3,4");
        zoomInButton.visible = true;
        zoomOutButton.visible = true;
    }
}

1. Create movieclips instance name of bg, zoomInButton, zoomOutButton

Out put :-

swap depth using 'contains' keyword

var a:MovieClip = new MovieClip();
a.graphics.beginFill(0xFF0000);
a.graphics.drawRect(0,0,200,200);
a.graphics.endFill();
addChild(a);
var b:MovieClip = new MovieClip();
b.graphics.beginFill(0x00FF00);
b.graphics.drawRect(0,0,200,200);
b.graphics.endFill();
b.x = 350;
addChild(b);
var c:MovieClip = new MovieClip();
c.graphics.beginFill(0x0000FF);
c.graphics.drawCircle(0,0,50);
c.graphics.endFill();
a.addChild(c);

stage.addEventListener(MouseEvent.CLICK, swapChild);

function swapChild(e:MouseEvent){
    if(a.contains(c)){
        b.addChild(c);
    }else{
        a.addChild(c);
    }
}

How to set depth index in action script



var aindex = getChildIndex(a);
var bindex = getChildIndex(b);
var cindex = getChildIndex(c);
trace(aindex);
trace(bindex);
trace(cindex);
xx.addEventListener(MouseEvent.CLICK, clickScrollerItem);
function clickScrollerItem(e:MouseEvent):void
{
    //setChildIndex( bindex, 0);
   

    if (a > b)
    {
        setChildIndex(a,b.numChildren);
    }
    if (a < b)
    {
        setChildIndex(a,b.numChildren-1);
    }
    trace(aindex);
    trace(bindex);
    trace(cindex);
}

1. Create a movieclips with the instance names a,b,c,d.

Arrange as per the Fig below and press Ctrl+Enter to check output :

0
1
2



play sound using button in action script 3.0





var my_sound:SoundId = new SoundId();
var my_channel:SoundChannel = new SoundChannel();


play_btn.addEventListener(MouseEvent.CLICK, playSound);
stop_btn.addEventListener(MouseEvent.CLICK, stopSound);


function playSound(event:MouseEvent):void{
my_channel = my_sound.play();
}


function stopSound(event:MouseEvent):void{
my_channel.stop();
}


1. Create play button instance of 'play_btn'.
2. Create stop button instance of 'stop_btn'.


Wednesday 19 December 2012

character moves using stage clicks in as3




var iswalking = false;
var goX = char.x;
var goY = char.y;
var movespeed = 5;
var dir = "down";
stage.addEventListener(Event.ENTER_FRAME, loop);
function loop(Event)
{// animation handling
if (iswalking == true)
{
char.w.play();
}
else
{
char.w.gotoAndStop(1);
}// direction handling
char.gotoAndStop(dir);// movement handling
if ((goY-movespeed)>char.y)
{
char.y +=  movespeed;
dir = "down";
iswalking = true;
}
else if ((goY+movespeed)<char.y)
{
char.y -=  movespeed;
dir = "up";
iswalking = true;
}
else if ((goX-movespeed)>char.x)
{
char.x +=  movespeed;
dir = "right";
iswalking = true;
}
else if ((goX+movespeed)<char.x)
{
char.x -=  movespeed;
dir = "left";
iswalking = true;
}
else
{
iswalking = false;
}
}
bg.addEventListener(MouseEvent.CLICK, setposition);
//bg.addEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler);
//bg.addEventListener(MouseEvent.MOUSE_UP, mouseUpHandler);


function setposition(event:MouseEvent):void
{
goX = mouseX;
goY = mouseY;
}

function mouseDownHandler(event:MouseEvent):void
{
bg.startDrag(true);
bg.x=mouseX;
    bg.y=mouseY;
}
function mouseUpHandler(event:MouseEvent):void
{
bg.stopDrag();
//bg.removeEventListener(MouseEvent.CLICK, setposition);
}

Animation : -

1. create character frames front, back, left and right.
2. create a background with the instance name of 'bg'

loader using URLEvent action script 3





var request:URLRequest = new URLRequest("http://www.actionscriptworkouts.blogspot.in/");
var loader:Loader = new Loader();

loader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, loadProgress);
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, loadComplete);

function loadProgress(event:ProgressEvent):void {
var percentLoaded:Number = event.bytesLoaded/event.bytesTotal;
percentLoaded = Math.round(percentLoaded * 100);
trace("Loading: "+percentLoaded+"%");
text1.text = "Page loading.... "+percentLoaded+"%";
}
function loadComplete(event:Event):void {
trace("Complete");
}

loader.load(request);
addChild(loader);

output :-



loader bar using mouse click event



code : -

var count_clean:Number=0;
bar_clean.visible = false;
a.addEventListener(MouseEvent.CLICK, afun);
function afun(e:Event) {
bar_clean.visible = true;
count_clean++;

bar_clean.scaleX=count_clean/10;
if (count_clean==10) {
a.removeEventListener(MouseEvent.CLICK, afun);
}

trace("kkk"+count_clean);
}




1. create a button using instance name of 'a'.
2. create a movieclip using instance name of 'bar_clean'




out put : -


Hit test object bounds bmp data in actionscript


1. create movieclip with the instance name of 'laserGun'
2. create movieclip with the instance name of 'redClip'



code :-


addEventListener(Event.ENTER_FRAME, enterFrame);

function enterFrame(e:Event):void
{
laserGun.x = mouseX;
laserGun.y = mouseY;


var laserRect:Rectangle = laserGun.getBounds(this);
var laserOffset:Matrix = laserGun.transform.matrix;
laserOffset.tx = laserGun.x - laserRect.x;
laserOffset.ty = laserGun.y - laserRect.y;

var laserGunBmpData = new BitmapData(laserRect.width,laserRect.height,true,0);
laserGunBmpData.draw(laserGun, laserOffset);

var redRect:Rectangle = redClip.getBounds(this);
var redClipBmpData = new BitmapData(redRect.width,redRect.height,true,0);

var redOffset:Matrix = redClip.transform.matrix;
redOffset.tx = redClip.x - redRect.x;
redOffset.ty = redClip.y - redRect.y;

redClipBmpData.draw(redClip, redOffset);

var rLoc:Point = new Point(redRect.x,redRect.y);
var bLoc:Point = new Point(laserRect.x,laserRect.y);

if (redClipBmpData.hitTest(rLoc,
255,
laserGunBmpData,
bLoc,
255
 ))
{
trace("Hit");

}
else
{
trace("No Hit");
}

laserGunBmpData.dispose();
redClipBmpData.dispose();
}

output look like :-





collision detection using hittestobject in as3



1. create movieclip with instance name of 'star'.
2. create movieclip with instance name of 'circle'.
3. create one dynamic text box with the instance name of 'messageText'.

code : -


// move star with mouse
addEventListener(Event.ENTER_FRAME, test_fun1);

function test_fun1(event:Event):void {
star.x=mouseX;
star.y=mouseY;


// test star versus circle
if (star.hitTestObject(circle)) {
messageText.text="collide";
} else {
messageText.text="Not collide";
}
}

output looks like :-




gradient background using as2 code




wSize = Stage.width;
hSize = Stage.height;
fillType = "linear";
colors = [0xFF0000, 0xFFFF00];
alphas = [100, 100];
ratios = [0, 255];
matrix = {matrixType:"box", x:0, y:0, w:wSize, h:hSize, r:90/180*Math.PI};
_root.lineStyle(1, 0xFFFFFF, 0);
_root.beginGradientFill(fillType, colors, alphas, ratios, matrix);
_root.lineTo(wSize, 0);
_root.lineTo(wSize, hSize);
_root.lineTo(0, hSize);
_root.lineTo(0, 0);
_root.endFill();


out put looks like :-



gradient background using as3 code



var rect:Shape=new Shape();
this.addChild(rect);
rect.x = 0;
rect.y = 0;
var rectWidth:Number = 640;
var rectHeight:Number = 480;
var mat:Matrix;
var colors:Array;
var alphas:Array;
var ratios:Array;
mat=new Matrix();
colors = [0x000000,0x006699];
alphas = [1,1];
ratios = [0,255];
mat.createGradientBox(rectWidth,rectHeight,toRad(-90));
rect.graphics.lineStyle();
rect.graphics.beginGradientFill(GradientType.LINEAR,colors,alphas,ratios,mat);
rect.graphics.drawRect(0,0,rectWidth,rectHeight);
rect.graphics.endFill();
function toRad(a:Number):Number
{
return a*Math.PI/180;
}

Out put looks like :-


glow filter effect on mouse-over in as3

1. create a movieclip with the instance name of 'robot'



import flash.filters.*;

//This creates a new GlowFilter that we can then assign to a movieclip on the stage
var robotGlow:GlowFilter = new GlowFilter();
//The color of the GlowFilter
robotGlow.color = 0x138613;
//The size of the filter on the x-axis
robotGlow.blurX = 50;
//The size of the filter on the y-axis, these don't have to be the same
robotGlow.blurY = 50;
//Setting the alpha of our filter to zero to start off with
robotGlow.alpha = 0;
//Assigning the GlowFilter to the robot movieclip
robot.filters = [robotGlow];
//This will tell our filter when to turn on and off
var glow:Boolean = false;

//Our listeners

addEventListener(Event.ENTER_FRAME, increaseGlow);

//This function sets glow to true which turns on the glow when the mouse cursor is over our movieclip
function addGlow(e:MouseEvent):void
{
    robotGlow.alpha = 100;
glow = true;
}

//This turns off the glow when the mouse cursor leaves the movieclip
function removeGlow(e:MouseEvent):void
{
    robotGlow.alpha =0;
glow = false;  
}

//This checks the status of glow and turns on and off our glow
function increaseGlow(e:Event):void
{
    robot.addEventListener(MouseEvent.MOUSE_OVER, addGlow);
robot.addEventListener(MouseEvent.MOUSE_OUT, removeGlow);
    robot.filters = [robotGlow];
}



Out put looks like :-



Drop down list in actionscript3 using transitions effects


//Import the required classes
import fl.transitions.Tween;  
import fl.transitions.easing.*;
import fl.transitions.TweenEvent;

//Turn on buttonMode for our movieclips
button_mc.buttonMode=true;
dropdown_mc.buttonMode=true;

//Add the dropDown Event Listener
button_mc.addEventListener(MouseEvent.CLICK, dropDown);

//initial dropDown function to animate on our dropdown movieclip into the mask
function dropDown(e:MouseEvent):void
{
var enterTween:Tween;
enterTween = new Tween(dropdown_mc, "y", Regular.easeOut, dropdown_mc.y,  177, 30, false);
enterTween.addEventListener(TweenEvent.MOTION_FINISH, dropUpEventListener);
}

//This function is called on after the dropdown animation is finished
function dropUpEventListener(e:TweenEvent):void
{
button_mc.removeEventListener(MouseEvent.CLICK, dropDown);  //remove event listener to dropDown function
button_mc.addEventListener(MouseEvent.CLICK, dropUp);  // add event listener for dropUp function
}

//Drop up function tweens out our dropdown movieclip from the mask
function dropUp(e:Event):void
{
var enterTween:Tween;
enterTween = new Tween(dropdown_mc, "y", Regular.easeOut, dropdown_mc.y,  -8, 30, false);
enterTween.addEventListener(TweenEvent.MOTION_FINISH, dropDownEventListener);
}

//Function does the exact opposite of the dropUpEventListener
function dropDownEventListener(e:TweenEvent):void
{
button_mc.removeEventListener(MouseEvent.CLICK, dropUp);
button_mc.addEventListener(MouseEvent.CLICK, dropDown);
}

How to convert movie clip to bitmap in action script 3.0


var bitmapInfo:BitmapData = new BitmapData(myClip.width,myClip.height);
bitmapInfo.draw(myClip);
var bm:Bitmap = new Bitmap(bitmapInfo);
addChild(bm);



Friday 7 December 2012

load as2 swf in as3

SWF files written in ActionScript 1.0 or 2.0 cannot load SWF files written in ActionScript 3.0.

"0
1
ArgumentError: Error #2180: It is illegal to move AVM1 content (AS1 or AS2) to a different part of the displayList when it has been loaded into AVM2 (AS3) content.
    at flash.display::DisplayObjectContainer/addChild()
    at swfloading_fla::MainTimeline/onCompleteHandler()
"

How to load .swf file using action script 3.0


import flash.net.URLRequest;
import flash.display.Loader;
import flash.events.Event;
import flash.events.ProgressEvent;

function startLoad() {
    var mLoader:Loader = new Loader();
    var mRequest:URLRequest=new URLRequest("SampleSWFFile.swf");
    mLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, onCompleteHandler);
    mLoader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, onProgressHandler);
    mLoader.load(mRequest);
}

function onCompleteHandler(loadEvent:Event) {
    addChild(loadEvent.currentTarget.content);
}
function onProgressHandler(mProgress:ProgressEvent) {
    var percent:Number=mProgress.bytesLoaded/mProgress.bytesTotal;
    trace(percent);
}
startLoad();