Tuesday, 29 June 2010

Add dynamic instances to an array

Let’s say you have the following scenario, you have multiple movie clips in the library that you want to add dynamically into an array. There are two ways I discovered that this can be achieved. The first method involves writing out all the class names in an array like below. The code below assumes you have three movie clips in the library with class names: shape1, shape2, and shape3.

var shapeArray:Array = new Array (new Shape1(), new Shape2(), new Shape3()); 

This method works fine, but what if you have more than five movie clips in the library. For example, you have twenty movie clips or more that you wish to add into an array. You can use the same method as above although you would need to write out a lot of code. To make your life easier you can use the getDefinitionByName() method to get the name references for all the movie clips in the library. The code assumes you have ten movie clips in the library.

var numOfShape:uint = 10;
var shapeArray:Array = new Array();

for(var i:uint = 1; i < numOfShape+1; i++){
    var ShapeClass:Class= getDefinitionByName ("Shape"+i) as Class;
    shapeArray.push(new ShapeClass())
}

The code works by getting the class names of the Movie clip using the getDefinitionByName() method and pushing the values into an array.

Monday, 28 June 2010

Magic 8 ball tutorial in AS3 part 3

This is part 3 of the Magic 8 ball tutorial where you will learn how to add a shake effect to the 8 ball. Be sure you have completed part 1 of the tutorial as addition code will be added to this one.


Magic 8 ball tutorial in AS3 part 3

Step 1


On the timeline select the first frame and open up the Actions panel. Delete the following line of code from the showAnswers() function.

TweenLite.to(magic8Back_mc.output_mc, 3, {autoAlpha:1});
And then replace it with the following lines of code.
//This creates a new instance of the Timer class which will run once with a delay 
//of 2seconds.
var myTimer:Timer=new Timer(2000,1);

//This is a timer event to set up the timer intervals.
myTimer.addEventListener(TimerEvent.TIMER, moveBack);

//The start() method starts the timer. 
myTimer.start();

//Adds an enter frame event to the 8 ball. 
magic8Back_mc.addEventListener(Event.ENTER_FRAME,shakeEffect);

Step 2

Outside of the showAnswers() function add the remaining code below.
//This function add the shake effect to the magic 8 ball. 
function shakeEffect(event:Event):void {
    var shakeAmount:uint=4;
    var randomAction:int=Math.floor(Math.random()*2);
    if (randomAction==0) {
        event.target.x+=shakeAmount;
        event.target.y+=shakeAmount;
    } else if (randomAction == 1) {
        event.target.x-=shakeAmount;
        event.target.y-=shakeAmount;
    }
}

//This function removes the shake effect and sets the 8 ball back to it original position. 
//The inner triangle message will also fade in.
function moveBack(event:TimerEvent):void {
    magic8Back_mc.removeEventListener(Event.ENTER_FRAME,shakeEffect);
    magic8Back_mc.x = 90;
    magic8Back_mc.y = 61; 
    TweenLite.to(magic8Back_mc.output_mc, 3, {autoAlpha:1});
}

Step 3

Test your movie Ctrl + Enter and you should now see a shake effect when you selected the magic 8 ball.

Monday, 21 June 2010

Number of objects on stage in AS3

If you ever want to tell how many objects there are on the stage, you can use the following code below. This code is useful if you are adding multiple movie clips dynamically on the stage and want to quickly see if the correct numbers have been added.

trace(this.numChildren, “number of objects on the stage”);

Sometimes it is hard to determine a movie clip depth/index on the stage. You can find out the index of an objects instance by using getChildAt() method, so the code below will give you the instance name of the object at the index 1.

trace(this.getChildAt(1), “the depth at index 1”); 

The getChildIndex() method from code below is like the opposite of the getChildAt() method. You give the objects instance name and the index gets returned.

trace(this.getChildIndex(yourInstanceName), “the depth of  yourInstanceName”);

If you have more than one object on the stage and you want to get the instance name of the object. You can use the numChildren property to get the number of objects on the stage, and use the getChildAt() method inside a For loop to get the instances name like below.

for(var i:uint = 0; i < numChildren; i++){
trace(getChildAt(i).name)
}

This also works if you have multiple objects inside a movie clip, you would do this.

for(var i:uint = 0; i < nameOfMovieClip.numChildren; i++){
trace(nameOfMovieClip.getChildAt(i).name)
}

One of the main reasons for using the code above is saving time and speed. If you have twenty movie clips on the stage and you want instance names in an array, you can use the code below instead of typing out all the names individually into an array.

var myArray:Array = new Array();
for(var i:uint = 0; i < numChildren; i++){
myArray.push(getChildAt(i).name)
}

Parse XML in Actionscript 2

This is an older post I found on my computer that I forgot to upload back when I was using Actionscript 2. It’s a simple example of parsing XML in AS2, the code will basically display the attribute values from the XML to dynamic text fields on the stage.


Step 1

Open up your favourite text editor and type the following XML and save it as foods.xml into the same directory as your FLA file.


Step 2

Open a new AS2 file and select the Text tool with dynamic text and drag three text fields on the stage. Give the following instance names accordingly: name_txt, count_txt and type_txt.

Step 3

On the timeline insert a new layer called AS and then enter the following code into the Actions panel.
var myXML:XML = new XML();
myXML.ignoreWhite = true;
myXML.load("foods.xml");
myXML.onLoad = function(success) {
    if (success) {    
    
    var foodName  = myXML.firstChild.childNodes[0].attributes.name;
    var foodCount = myXML.firstChild.childNodes[0].attributes.count;
    var foodType   = myXML.firstChild.childNodes[0].attributes.type;

    name_txt.text = foodName;
    count_txt.text = foodCount;
    type_txt.text = foodType;
    
    }

}

Step 4


Test your movie Ctrl + Enter and you should see the data from the XML displayed in the text fields.

Friday, 18 June 2010

Text to uppercase in Actionscript 3

When you copy and paste uppercase letters into Flash sometimes it turns the letters into lowercase. I’ve been converting a lot of arbitrary text to uppercase recently, so have come up with a simple function to avoid manually typing each character into uppercase characters. I've used the toUpperCase() method in the String class which basically turns all the characters into uppercase.

var myString:String = "hello ilike2flash";

function turnUpperCase(uppStr:String):String{
    return uppStr.toUpperCase();    
}

trace(turnUpperCase("hello ilike2flash")); //HELLO ILIKE2FLASH 

If you wish to only turn the first characters in a string to uppercase, you can use the charAt() method to get the first letter and the substring method to get the remaining characters in the string.

var myString:String = "hello ilike2flash";

function firstUpperCase(firUpp:String):String{
    return firUpp.charAt(0).toUpperCase() + firUpp.substring(1,firUpp.length);
}

trace(firstUpperCase(myString)); //Hello ilike2flash

To reverse the uppercase characters you can use the toLowerCase() method which will convert all the uppercase characters into lowercase.
var myString:String = "SOME UPPERCASE CHARACTER"

trace(myString.toLowerCase()); //some uppercase character  

Monday, 14 June 2010

Remove characters from Strings in AS3

If you want to remove characters in a string, you can use the split and join properties in the String and Array Class. For example, to remove dashes from a string you can use the following.

var myText:String ="This-is-some-random-text";
var newString:String = myText.split("-").join(" ");
trace(newString); // This is some random text
The split property removes any characters specified inside the parameters. And the join property inserts a separator between the split elements. So, in the above example the separator is a space. Below is another example, but instead of joining using a space I have used a plus sign which will add a plus.
var myText:String ="This-is-some-random-text";
var newString:String = myText.split("-").join("+");
trace(newString); // This+is+some+random+text
If you have multiple strings that you want to remove characters from, you can create a function to do the hard work.
var number1:String = "000-111-222";
var number2:String = "333-444-555";
var number3:String = "666-777-888";

function thingToRemove(_text:String) {
    var myText:String=_text;
    var newString:String=myText.split("-").join(" ");
    return newString;
}

trace(thingToRemove(number1)); //000 111 222
trace(thingToRemove(number2)); //333 444 555
trace(thingToRemove(number3)); //666 777 88811
You can also do the opposite and remove white spaces from a string instead of replacing it with a character.
var myText:String = “This is some more text”;
var newString:String = myText.split(" ").join("");
trace(myText); // Thisissomemoretext

Thursday, 10 June 2010

Disappearing text effect class in AS3

I created the Disappearing text effect tutorial nearly a year ago. I used timeline animations to make the individual letters disappear one after another. I have decided to create a Disappearing text effect class to make the process of creating this text effect quicker. You will need to download the TweenLite plugin for this class. Below is the code.

package com.ilike2flash{

    import flash.display.MovieClip;
    import flash.events.Event;
    
    import com.greensock.*;

    public class DisappearText extends MovieClip {

        private var lettersArray:Array;
        private var counter:uint=0;
        
        public function DisappearText(lettArr:Array) {
            lettersArray=lettArr;
            setLetterFade();
            startFade();            
        }
            
        private function setLetterFade():void {
            for (var j:int=0; j
                lettersArray[j].alpha=0;
            }
        }

        private function startFade():void {
            TweenLite.to(lettersArray[counter],1,{alpha:1,onComplete:playNextFade});
        }

        private function playNextFade():void {
            if (counter==lettersArray.length-1 ) {
                counter=0;    
            }
            else {
                counter++;
                startFade();
            }
        }
    }
}


To use this class, you need to do step 1 & 2 of this tutorial. Then add all the movie clip instances to an array called mcArray and add the following code.
import com.ilike2flash.DisappearText;

var myDText:DisappearText = new DisappearText(mcArray);
addChild(myDText);

Thursday, 3 June 2010

Image roll over effect AS3 code

I wrote the Image rollover effect tutorial quite a while ago. I have now decided to write an Actionscript 3 code version of this tutorial. This means that if you use lots of images it will take less time to create. The step up for this tutorial is similar to the previous, but you wont’ need any motion tweens in the timeline. I have also used the tweenlite plugin for the tweening effect.


Image roll over effect AS3 code

Step 1

Open a new AS3 file. Then import all the images you wish to use by selecting File > Import > Import to Library. Drag the individual images from the library onto separate layers on the timeline, so each layer only contains one image.


Step 2

Convert each of your images into movie clips (F8) and give them following instance names accordingly: image1_mc, image2_mc etc.


Step 3

On the timeline create a new layer called AS and then open up the Actions panel (F9) and enter the following code.

//Import the tweenlite packages.
import com.greensock.*;

//Array to hold all the movie clip instances.
var mcArray:Array=[ image1_mc, image2_mc, image3_mc];

//Counter to hold the position of the array.
var counter:uint=0;

//Adds the mouse over event to all the images.
for (var i:uint = 0; i < mcArray.length; i++) {
mcArray[i].addEventListener(MouseEvent.MOUSE_OVER,imageOver);
}


//This function causes the images to fade out when moused over.
function imageOver(event:MouseEvent):void {
TweenLite.to(mcArray[counter],1,{alpha:0, onComplete:playNext});
}


//This function increments the counter and moves the second image on the timeline to
//top of the stack. When all the images have faded out, the counters get reset and all
//the images fade back to with the first image on the top of the stack.
function playNext():void {
if (counter==mcArray.length-1) {
counter=0;

setChildIndex(mcArray[0], numChildren - 1);

for (var ii:uint = 0; ii < mcArray.length; ii++) {
TweenLite.to(mcArray[ii],1,{alpha:1});
}

} else {
counter++;
setChildIndex(mcArray[counter], numChildren - 1);
}
}

Step 4

Test your movie Ctrl + Enter.

  COPYRIGHT © 2011 · ILIKE2FLASH · Theme by Ourblogtemplates

Back to TOP