Wednesday, 27 April 2011

Load multiple external swf in AS3

I previously wrote a post about loading a single external swf in Actionscript 3. In this post I will write about loading multiple external swf’s in Actionscript 3. A common problem you face when loading more than one swf is that multiple copies can potentially be loaded. Look at the example below.

btn1.addEventListener(MouseEvent.CLICK, loadSwf1);
btn2.addEventListener(MouseEvent.CLICK, loadSwf2);

function loadSwf1(e:MouseEvent):void{
 var loader1:Loader  = new Loader(); 
 loader1.load(new URLRequest("exampleA.swf"));
 addChild(loader1);
}


function loadSwf2(e:MouseEvent):void{
 var loader2:Loader = new Loader(); 
 loader2.load(new URLRequest("exampleB.swf"));
 addChild(loader2);
 loader2.x = 100; 
}

The two external swf’s are being loading in from a button click. The code above will work, but multiple copies of the swf will be loaded every time you press the buttons which is no good. The solution is to load the swf’s into container sprites and perform a check to see how many child objects exist before loading the swf. In the example below I have loaded the swf’’s into separate containers and added an If statement to check if the number of children is less than one. This means that only one copy of the swf can exist inside the container.

var container1:Sprite = new Sprite();
var container2:Sprite = new Sprite();
addChild(container1);
addChild(container2);

btn1.addEventListener(MouseEvent.CLICK, loadSwf1);
btn2.addEventListener(MouseEvent.CLICK, loadSwf2);

function loadSwf1(e:MouseEvent):void{
 if(container1.numChildren < 1){
  var loader1:Loader = new Loader(); 
  loader1.load(new URLRequest("exampleA.swf"));
  container1.addChild(loader1);
 }
 trace("Number of children in container1 is:" + container1.numChildren);
}


function loadSwf2(e:MouseEvent):void{
 if(container2.numChildren < 1){
  var loader2:Loader = new Loader(); 
  loader2.load(new URLRequest("exampleB.swf"));
  loader2.x = 100;
  container2.addChild(loader2);
 }
 trace("Number of children in container2 is:" + container1.numChildren);
}

Alternatively, if you wish to remove an external swf before loading a new one in. You can repeat the same as above, but you will only need to use one container. Take a look the example below. As you can see I have used a While statement inside the clickHandler function to check that only one child exists inside the container.

var container:Sprite = new Sprite();
addChild(container);

btn1.addEventListener(MouseEvent.CLICK, clickHandler);
btn2.addEventListener(MouseEvent.CLICK, clickHandler);

function clickHandler(e:Event):void{
 
 while(container.numChildren == 1) container.removeChildAt(0);
 
 switch(e.target.name){
  case "btn1": loadSwf("exampleA.swf"); break;
  case "btn2": loadSwf("exampleB.swf"); break;
 } 
 
 trace("Number of children in container is:" + container.numChildren);
}

function loadSwf(swfName:String):void{
 var loader:Loader = new Loader(); 
 loader.load(new URLRequest(swfName));
 container.addChild(loader);
}

The code below is another method of adding in new swf’s. This time I have not used a container to hold the swfs. The new loaded swf will get overwritten by the old one, so you don’t need to check if there are multiple copies.

btn1.addEventListener(MouseEvent.CLICK, clickHandler);
btn2.addEventListener(MouseEvent.CLICK, clickHandler);

var loader:Loader = new Loader(); 
addChild(loader);

function clickHandler(e:Event):void{

  switch(e.target.name){
    case "btn1": loader.load(new URLRequest("exampleA.swf")); break;
    case "btn2": loader.load(new URLRequest("exampleB.swf")); break;
  } 
}

Monday, 18 April 2011

Blur guess game in AS3 part 1

In this tutorial you will learn how to create a Blur guess game in Actionscript 3. In this game you will see blurry images and you need guess the name object in the blurry image. For this tutorial you will need logo images, I have used famous brand logo which can be downloaded at: brandsoftheworld.com/

Update: Blur guess game part 2

Blur guess game in Actionscript 3


Step 1

Open a new AS3 file and import your images into the stage by selecting File > Import > Import to stage. Before you import your images, make sure they are the same width and height. My images dimensions are 100x100 pixels. You can use Photoshop or a similar program to edit the dimensions of the images.


Step 2

Arrange the images on the stage, so that there are in 3 columns like below. And convert them into movie clips with the instance names: youtube_mc, mastercard_mc, ibm_mc, canon_mc, shell_mc and bmw_mc.



Step 3


Select the Text tool with input text and drag a text field on the stage. Give the instance name: input_txt. Then drag another text field, but this time with dynamic text and give the instance name: found_txt. You will need to embed the numerals and a ‘/’ (forward slash) glyphs.


Step 4

Open up a new AS3 class file save the file name as ‘BlurGuess’ and add the following code.

package {

 import flash.filters.BlurFilter;
 import flash.display.*;
 import flash.events.MouseEvent;
 import flash.events.Event;
 import flash.utils.setTimeout;

 public class BlurMatch extends MovieClip {

  private var wordsMcArray:Array = new Array  ;
  private var strArray:Array = new Array  ;
  private var mcCheckArray:Array = new Array  ;

  private var counter:uint = 0;
  private var totalWords:uint;
  private var cols:uint = 3;
  private var xOffset:Number = 133.30;
  private var yOffset:Number = 121.95;


  public function BlurMatch() {
   init();
  }

  private function init():void {
   wordsMcArray = [youtube_mc,mastercard_mc,ibm_mc,canon_mc,shell_mc,bmw_mc];
   strArray = ["youtube","master","ibm","canon","shell","bmw"];
   mcCheckArray = [];

   counter = 0;
   totalWords = strArray.length;

   //Displays the number of correct words answered and set the focus to the input text field.
   found_txt.text = String(counter) + "/" + String(totalWords) + "correct";
   stage.focus = input_txt;


   for (var j:int = 0; j < wordsMcArray.length; j++) {
    //Adds a blur and outline to each of the image
    wordsMcArray[j].filters = [new BlurFilter(15,15,3)];

    var outLine:Shape = new Shape  ;
    outLine.graphics.lineStyle(2,0x000000);
    outLine.graphics.drawRect(wordsMcArray[0].x + xOffset * j % cols,wordsMcArray[0].y + yOffset * int(j / cols),wordsMcArray[0].width + 2,wordsMcArray[0].height + 2);
    outLine.graphics.endFill();
    addChild(outLine);
   }

   //Adds the change event to the input text field.
   input_txt.addEventListener(Event.CHANGE,detectKeys);
  }

  private function detectKeys(e:Event):void {
   for (var i:int = 0; i < strArray.length; i++) {
    if (strArray[i] == input_txt.text.toLowerCase()) {
     trace('correct');
     //If the correct word is typed then the counter gets incremented and the
     //found displayed is updated to show a word has been found.
     counter++;
     found_txt.text = String(counter) + "/" + String(totalWords) + "correct";

     //This adds the correct word into the mcCheckArray.
     mcCheckArray.push(wordsMcArray[i]);

     //This removes the correct word from wordsMcArray and the strArray.;
     wordsMcArray.splice(wordsMcArray.indexOf(wordsMcArray[i]),1);
     strArray.splice(strArray.indexOf(strArray[i]),1);

     //Removes the movie clip blur filter.
     mcCheckArray[mcCheckArray.length - 1].filters = [];

     //This clear the text field after a half second delay
     setTimeout(function(){ input_txt.text = ""; },500);
    }
   }
  }
 }
}

Step 5

In the document class add the name: ‘BlurGuess’ then export the movie Ctrl + Enter. You should now have a blur guess game in Actionscript 3.



You can download the source files here.

Update: Blur guess game part 2

Sunday, 17 April 2011

Box zoom effect in Actionscript 3

In this post you will learn how to create a box zoom effect using Actionscript 3 code. This effect can be used in an image gallery such as the black and white gallery. When a box gets clicked on, it will get scaled up and when it’s clicked again it will get scaled down. You will need the TweenNano class for this tutorial which can be downloaded at: greensock.com


Box zoom effect in Actionscript 3

Step 1

Open up a new AS3 file with the stage dimensions 400x300. Then open the Actions panel and copy the following code.

//Import the tweening TweenNano and easing packages.
import com.greensock.TweenNano;
import com.greensock.easing.*;

//The number of the boxes and columms in the grid.
var numOfBoxes:uint = 20;
var cols:uint = 5;

//The spacing between each box.
var xOffset:Number = 70;
var yOffset:Number = 70;

//Array to hold the sprites and x and y positions.
var spriteArray:Array = new Array();
var sPosArray:Array = new Array();

//Holds the currently selected sprite and the index of array
var selectedSprite:Sprite;
var currentIndex:uint;

//This creates 20 sprite on the stage with random colours and
//adds the sprites into an arrray with the x and y positions.
for (var i:uint = 0; i < numOfBoxes; i++) {
           var s:Sprite = new Sprite();
           s.graphics.beginFill(Math.random() * 0xffffff);
           s.graphics.drawRect(0, 0, 50, 50);
           s.graphics.endFill();
           addChild(s);

           s.x = 35 + xOffset * (i%cols);
           s.y = 25 + yOffset * int(i/cols);
                       
           spriteArray.push(s);
           sPosArray.push({xpos:spriteArray[i].x, ypos:spriteArray[i].y})    
}

//Adds the mouse click event to the sprites.
function addListeners():void{
  for (var i:uint = 0; i < spriteArray.length; i++) {
      spriteArray[i].buttonMode = true;
      spriteArray[i].addEventListener(MouseEvent.CLICK, clickHandler);
  }
}

//Removes the mouse click event from the sprites.
function removeListeners():void{
  for (var i:uint = 0; i < spriteArray.length; i++) {
      spriteArray[i].buttonMode = false;
      spriteArray[i].removeEventListener(MouseEvent.CLICK, clickHandler);
  }
}

//This set the current selected sprite to the top of the display list,
//removes the mouse listeners and moves the sprite to the centre of the stage.
function clickHandler(e:MouseEvent):void{
  selectedSprite = e.currentTarget as Sprite;
  currentIndex = spriteArray.indexOf(e.currentTarget);
 
  setChildIndex(selectedSprite, numChildren - 1);
 
  removeListeners();
 
  TweenNano.to(selectedSprite, 1, {
               x:stage.stageWidth/2 - selectedSprite.width,
               y:stage.stageHeight/2 - selectedSprite.height,
                                               ease:Elastic.easeOut,
               onComplete: onCenter});
}

//This scales up the x and y and add an event listener to the selected sprite.
function onCenter():void{
  TweenNano.to(selectedSprite, 0.5, {scaleX:3, scaleY:3});
  selectedSprite.buttonMode = true;
  selectedSprite.addEventListener(MouseEvent.CLICK, spriteClick);
}


//When the sprite is clicked it returns to its original position and
//removes its mouse click listener.
function spriteClick(e:MouseEvent):void{
  TweenNano.to(selectedSprite, 1, {scaleX:1,
               scaleY:1,
               x:sPosArray[currentIndex].xpos,
               y:sPosArray[currentIndex].ypos,
                                               ease:Elastic.easeIn,
               onComplete:addListeners});
 
  selectedSprite.buttonMode = false;
  selectedSprite.removeEventListener(MouseEvent.CLICK, spriteClick);
}

addListeners();

Step 2

Export the movie Ctrl + Enter. Now click on the one the sprites and it should expand, and if you click it again it will contract.

Monday, 11 April 2011

Drag and drop in AS3 part 3

This is an addition to part 2 of the Drag and drop tutorial. In part 2 I modified the original code, so that multiple objects could use the same startDrag() and stopDrag() methods using the ‘event.target’ property. Since, then I have also created a drag and drop puzzle tutorial which also use the same functionality.

In this tutorial I will create a simple matching game using three targets and three draggable objects. In the game you match the draggable objects to the responding targets.


Drag and drop in AS3 part 3

Step 1

Open a new AS3 file. Then select the Rectangle tool and draw three targets on the stage like below. Convert each of the targets into movie clips (F8) with the centre registration point selected and give them the instance names: hitTarget1, hitTarget2 and hitTarget3 accordingly.



Step 2

Select the Oval tool and draw the draggable objects like below. Convert each of the targets into movie clips (F8) with the centre registration point and give them the instance names: drop1, drop2 and drop3 accordingly.




Step 3

On the timeline insert a new layer called ‘AS’ then open the actions panel and enter the following code:

//Array to hold the target instances, the drop instances,
//and the start positions of the drop instances.
var hitArray:Array = new Array(hitTarget1,hitTarget2,hitTarget3);
var dropArray:Array = new Array(drop1,drop2,drop3);
var positionsArray:Array = new Array();


//This adds the mouse down and up listener to the drop instances
//and add the starting x and y positions of the drop instances
//into the array.
for (var i:int = 0; i < dropArray.length; i++) {
dropArray[i].buttonMode = true;
dropArray[i].addEventListener(MouseEvent.MOUSE_DOWN, mdown);
dropArray[i].addEventListener(MouseEvent.MOUSE_UP, mUp);

positionsArray.push({xPos:dropArray[i].x, yPos:dropArray[i].y});
}

//This drags the object that has been selected and moves it
//to the top of the display list. This means you can't drag
//this object underneath anything.
function mdown(e:MouseEvent):void {
e.currentTarget.startDrag();
setChildIndex(MovieClip(e.currentTarget), numChildren - 1);
}

//This stops the dragging of the selected object when the mouse is
//released. If the object is dropped on the corresponding target
//then it get set to the x and y position of the target. Otherwise
//it returns to the original position.
function mUp(e:MouseEvent):void {
var dropIndex:int = dropArray.indexOf(e.currentTarget);
var target:MovieClip = e.currentTarget as MovieClip;

target.stopDrag();

if (target.hitTestObject(hitArray[dropIndex])) {
target.x = hitArray[dropIndex].x;
target.y = hitArray[dropIndex].y;
}else{
target.x = positionsArray[dropIndex].xPos;
target.y = positionsArray[dropIndex].yPos;
}
}
Here are some extras to spice up this game. I have created a button to reset the drop objects when they are all on the respective targets.
reset.addEventListener(MouseEvent.CLICK, backObjects);

function backObjects(e:MouseEvent):void{
for(var i:int = 0; i < dropArray.length; i++){
if(dropArray[i].x == hitArray[i].x && dropArray[i].y == hitArray[i].y){
dropArray[i].x = positionsArray[i].xPos;
dropArray[i].y = positionsArray[i].yPos;
}
}
}

I have also added a scream sound effect when the drag object is on the correct target. You will need to import a sound effect into the library then right click on the audio file and select properties, check the export to Actionscript button and give it a class name. For more information on sounds in Actionscript 3, checkout some of my audio tutorials.
function playSound(SoundName:Class):void{
var sound = new SoundName();
var channel:SoundChannel = sound.play();
}

To play the sound effect, add the following line of code inside the If statement of the mUp function.
playSound(TheNameOfTheClass);

Step 4

Test your movie clip Ctrl + Enter. You should now have a simple matching game.

Sunday, 10 April 2011

Word of the day in Actionscript 3

In this tutorial you will learn how to create a Word of the day application. The words are provided by the Yahoo word of the day RSS feed. Every day you will see a different word and definition in the application.

Word of the day in Actionscript 3

Step 1

Open a new Actionscript 3 file with the stage dimensions 400x250. Give the document class the name: 'WordDay'


Step 2

Select the Text tool with dynamic text and drag three text fields on the stage. Give them the instance names: title_txt, des_txt, and date_txt accordingly.


Step 3

Open a new AS3 class file and save the file as ‘WordDay’ then enter the following code:

package {

import flash.display.MovieClip;
import flash.net.URLLoader;
import flash.net.URLRequest;
import flash.events.Event;

public class WordDay extends MovieClip {

private var xml:XML;
private var titleText:String;
private var descriptionText:String;
private var loader:URLLoader;

public function WordDay() {
//Create a new instance of the URLLoader class and load the words rss feed.
loader = new URLLoader();
loader.addEventListener(Event.COMPLETE, xmlLoaded);
loader.load(new URLRequest("http://xml.education.yahoo.com/rss/wotd/"));
}


private function xmlLoaded(e:Event):void {
loader.removeEventListener(Event.COMPLETE, xmlLoaded);
xml = new XML(e.target.data);
titleText = xml.channel.item.title;
descriptionText = xml.channel.item.description;
addText();
}

//This function displays the parsed xml into the text fields.
private function addText():void {
title_txt.text = titleText.substring(0,titleText.indexOf("-"));
des_txt.text   = descriptionText;
date_txt.text  = titleText.substring(titleText.indexOf("-") + 2,titleText.length);
}
}
}

Note, that I have separated the title and date into two different text fields using the substring() method. If you trace out ‘titleText’ inside the xmlLoaded function you will see that the title and date are joined together.


Step 4

Test your movie clip Ctrl + Enter.

  COPYRIGHT © 2011 · ILIKE2FLASH · Theme by Ourblogtemplates

Back to TOP