Flash AS3 Preloader

I wanted to write a basic tutorial on creating a simple flash AS3 (actionscript 3) preloader. Also, I am going to talk about some of the issues that I came across during the process that might help out other designers and developers. You can see the preloader in action by clicking the image below and the code is below that. The comments in the code should help explain exactly what I am doing and be a basic tutorial for any beginner. This preloader is easy to use, just change one line of code, the line defining the name of the swf you want to load, and you can easily change the color too. The download link is below the code, but please give me credit when using it.

One of the first problems I encountered is when I add the url loader with this line of code, “addChild(loader);” Most other tutorials will tell you to put this in your eventlistener complete function, but I have come across several problems when doing that such as the ugly “1009 cannot access a property or method of a null object reference” error.” The reason you get this is because you are trying to do something with the loader before its actual loaded into memory. So I just add the “addChild(loader)” outside of any eventlistener and it resolves it. Then, I add another function inside of the eventlistener complete function to handle any tweens or effects on the preloader itself after its done loading.

Another problem I come across is the text field not fading away when tweening it. This is a textfield problem, I can’t explain why its doing it, it just is, so the work around there is to make it a movie clip and change that movieclip’s blend mode to anything but normal and then the tweens will handle it correctly.

Make sure to check out some of my advanced preloaders for sale on my activeden portfolio and please buy one if they spark your interest. A nicely designed preloader can really impress your client and its only costs a few bucks.

flashas3preloader

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
//import tweening libraries
import fl.transitions.Tween;
import fl.transitions.easing.*;
 
//stop command
stop();
 
//initalize percent, loaded, and total variables for preloader
var percent:Number = 0;
var loaded:Number;
var total:Number;
 
//intialize loader variable
var loader:Loader = new Loader();
 
//set up the listener for the loader object to get the progress of the download
loader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, getBytesLoop);
//set up the listener for the loader object to call loadingDone function when loading is done
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, loadingDone);
//set up the listener for the on enterframe event, this is called all the time
mypreloader.addEventListener(Event.ENTER_FRAME,preloaderMotion);
 
//load the swf you want
//***change this swf name to the one you want to load****
loader.load(new URLRequest("testContent.swf"));
 
//add the loader to the stage
addChild(loader);
 
//getbytesloop function sets the info of the loaded swf during the progress of the load
function getBytesLoop(e:ProgressEvent):void {
 
	//set the total and loaded variable for the progress of the preloader
	total = e.bytesTotal;
	loaded = e.bytesLoaded;
	percent = Math.floor((loaded / total) * 100);
 
	//make the text on the screen show how much is loaded
	textMC.myText.text = percent.toString();
}
 
//loadingDone function hides the preloader when its done
function loadingDone(e:Event):void {
	hidePreloader();
}
 
//preloader motion function give motion to the preloader, add effects here to make your preloader move
function preloaderMotion(e:Event):void {
	mypreloader.rotation += 5;
}
 
//hidepreloader function, fades away all the objects in the preloader and shows the loaded content on the screen
function hidePreloader():void {
	var myTween2:Tween = new Tween(mypreloader, "alpha", Strong.easeOut, 1, 0, 1, true);
	var myTween3:Tween = new Tween(textMC.myText, "alpha", Strong.easeOut, 1, 0, 1, true);
}

Download Flash AS3 Preloader

Cya

Flash ipod Style Volume Controller

I am almost finished with the mp3player that I have been working on. I will make a post once it gets live on Flashden.  I just wanted to share how the volume controller works and the code with it. As you will see, I used the Math.atan2 function which basically returns the arc tangent of a point, and I used this to get the angle of where the mouse is compared to where you slide it. Click and hold over the circle and then move your mouse while still holding the mouse down to see the circle rotating. Look to my comments in my code for further explanation.

ipodVolumeController

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
//create a boolean variable for when the volume button is being pushed, and variables for the new and old rotation of that button
var buttonCircleMovement:Boolean = false;
var newAngle:Number = 0;
var oldAngle:Number = 0;
 
//create the inital volume variables, start at .5 or 50% volume
var volumePercent:Number = .5;
var currentVolume:Number = .5
 
//masks the volume tracker to what the currentVolume is times the width of the volume bar
volumeTracker.volumeBarMask.width = 80 * currentVolume;
 
//on mouse down allow the the volume to change, on mouse up make it so the volume can't change
buttonCircle.addEventListener(MouseEvent.MOUSE_DOWN, volumeOn);
buttonCircle.addEventListener(MouseEvent.MOUSE_UP, volumeOff);
 
//add event listeners for mouse movements and call the button circle move functions for the button circle
buttonCircle.addEventListener(MouseEvent.MOUSE_MOVE, buttonCircleMove);
 
//function is called when the mouse is down on the circle movieclip
function volumeOn(e:MouseEvent):void {
 
	//set the button circle movement variable to true
	buttonCircleMovement = true;
	// get the initial angle of where your mouse click was before the rotating the object
	oldAngle = Math.atan2(buttonCircle.y - mouseY, buttonCircle.x - mouseX) * 180/Math.PI;
}
 
//function is called when the mouse is up off of the circle movieclip
function volumeOff(e:MouseEvent):void {
 
	//set the button circle movement variable to false
	buttonCircleMovement = false;
}
 
//function that controls the volume bar
function buttonCircleMove(e:MouseEvent):void {
 
	//if the button circle movement variable is set to true
	if (buttonCircleMovement) {
 
		//as your mouse moves, calculate the angle by where your mouse is located
		newAngle = Math.atan2(buttonCircle.y - mouseY, buttonCircle.x - mouseX) * 180/Math.PI;
 
		//make a temporary variable hold the difference between the new and old angle
		var tempVar = (newAngle - oldAngle) - 360 * Math.round((newAngle - oldAngle) / 360);
 
		//rotate the circle to the new angle that is being calculated
		buttonCircle.rotation = newAngle;
 
		//make the old angle where the new angle is now
		oldAngle = newAngle;
 
		//get the new volume percent by adding the old percent to the temporary variable divided by 360
		volumePercent = volumePercent + tempVar / 360;
 
		//if the volume percent is greater than 1 then just make it 1
		if (volumePercent >= 1) {
			volumePercent = 1;
		}
		//if the volume percent is less than 0 then just make it 0
		if (volumePercent <= 0) {
			volumePercent = 0;
		}
 
		//make the current volume equal to the volume percent
		currentVolume = volumePercent;
 
		//changes the width of the mask for the volume bar
		volumeTracker.volumeBarMask.width = 80 * currentVolume;
 
	}
}

Cya

Flash Text Ticker / Scrolling Text in Actionscript 3.0

Update: I have created a text ticker / scrolling text component based off of this tutorial that is integrated with a XML file so users have more options and can make easy changes.  Click the image below to learn more.

So I have been working on a mp3player that is designed similar to a ipod with a little bit different functionality. I needed the text fields to scroll back and forth so you could see all the text written inside of it, if the field was shorter than the width of the text. After looking around for a tutorial or another persons help and not finding a thing for Actionscript 3, I decided to write my own. I am using Tweenlite to handle the tweens because its really low on weight and its a very smooth and powerful tweening engine. I am almost done with the mp3player and I will show you that very soon, but I wanted to post an example of the scrolling text or flash ticker (as some people call them) to you first before then. The example and code is below. I use one movieclip with an instance name of item that has two items inside of it, a dynamic textfield holding the text and a mask to only show the part I want shown.

scrollingText

//import libraries
import flash.utils.*;
import flash.text.TextField;
import gs.*;
import gs.easing.*
 
//make the text too long for the textfield and assign the mask for it
item.menuItemText.text = "This text is too long to fit in this tiny textfield, here is the end";
item.menuItemText.mask = item.menuItemMask;
 
//call the scrollWords function
scrollWords();
 
//the scrollWords function
function scrollWords():void {
        //make the textfield wordwrap false and autosize to textFieldAutoSize.LEFT
	item.menuItemText.wordWrap = false;
	item.menuItemText.autoSize = TextFieldAutoSize.LEFT;
 
        //if the textwidth is longer than the masks width which is 173 then call goforwardtween
	if(item.menuItemText.textWidth &gt; 173) {
		goForwardTween(item.menuItemText);
	}
}
 
//go forward tween, on complete it calls go back tween
function goForwardTween(tf:TextField):void {
	TweenLite.to(tf, 3, {x:-(item.menuItemText.textWidth) + 163, delay:1, onComplete:goBackTween, onCompleteParams:[tf] });
}
 
//go back tween, on complete it calls go forward tween
function goBackTween(tf:TextField):void {
	TweenLite.to(tf, 3, {x:10, delay:1, onComplete:goForwardTween, onCompleteParams:[tf] });
}

Cya

Update: WordPress and Flash Integration part III

Well, I finally had a little bit of free time and I wanted to rework all my wordpress and flash integrations stuff into ActionScript 3.  There were a couple of interesting things that came up while working on this as well.  You can’t tween the alpha property of a textfield created in actionscript (unless you use a simple hack that I found out in the Flash live-docs online).  You have to change the blendmode style to “LAYER”, or another type, as long as its not the default style type. Weird but at least I got it to work. Also, I was going to implement the tweens using TweenLite but they also have problems accessing textfield properities, too.

Here is the swf, and below is the actionscript 3:

wordpressflashex4

package  {
    import flash.display.MovieClip;
    import flash.display.BlendMode;
    import flash.events.Event;
    import flash.net.URLLoader;
    import flash.net.URLRequest;
    import flash.text.*;
    import fl.transitions.Tween;
    import fl.transitions.TweenEvent;
    import fl.transitions.easing.*;
 
    /*
    * Redo of scott rockers's wordpress to flash integration but in AS3 and as3wordpressFlash class file
    */
    public class AS3WordpressFlash extends MovieClip {
 
        public var i:uint = 0;
        public var titleList:XMLList;
        public var linkList:XMLList;
        public var tf:TextField;
        public var format:TextFormat;
        public var tweenIt:Tween;
        public var tweenIt2:Tween;
        public var theXML:XML;
        public var loader:URLLoader = new URLLoader();
 
        public function AS3WordpressFlash() {
            loader.addEventListener(Event.COMPLETE, loadXML);
            loader.load(new URLRequest("http://www.scottrockers.com/blog/wp-rss2.php"));
        }
 
        function loadXML(e:Event):void {
            theXML = new XML(e.target.data);
            titleList = theXML.channel.item.title;
            linkList = theXML.channel.item.link;
            createTextFields(titleList, linkList);
        }
 
        function createTextFields(titles:XMLList, links:XMLList):void {
            format = new TextFormat();
            format.font = "Arial";
            format.color = 0xFFFFFF;
            format.size = 14;
 
            for (i = 0; i &lt; 5; i++) {
                tf = new TextField();
                tf.blendMode = BlendMode.LAYER;
                tf.width = 10;
                tf.selectable = false;
                tf.autoSize = TextFieldAutoSize.CENTER;
                tf.x = (stage.width)/2;
                tf.y = -20;
                tf.htmlText = "<a href="&quot;+ links[i] +&quot;" target="_blank">" + titles[i] + "</a>";
                tf.setTextFormat(format);
                addChild(tf);
                tweenIt = new Tween(tf, "y", Elastic.easeOut, -20, 50 + (i * 30), 30 + (i * 15), false);
                tweenIt2 = new Tween(tf, "alpha", Strong.easeOut, 0, 1, 100 + (i * 100), false);
            }
        }
    }
}

Update: WordPress and Flash Integration part II

After working on accessing WordPress through the RSS feed with Flash, I have finally achieved what I was aiming for:  I wanted to be able to tween the headings of each post individually as well as make them links to the actual post.  Also, as you will see, this swf is dynamic meaning it will update itself to have the most recent blog post headings. Here is what I came up with:

I did come across a few interesting things. When accessing the titles of each heading, I used “.nodeValue”, but when accessing the links of the headings I had to use “theNodePath.toString()”. I thought this was weird because all the information looked the same inside each node in the XML.

I will use this technology on my blog as well as my Flash site, once I get some time to work on them. Hopefully soon, because I am pumped that I figured out how to do this.

Cya