I built a gallery with actionscript 3 that runs off xml. Below you can view it or download the source files.
[ SEE IT IN ACTION ]
[ DOWNLOAD THE FILES ]
Issues this covers: ActionScript 3, AS3, Gallery, XML, Preloader, Preload external files, Tween Class, enterframe, Mouse events, Arrays, addChild, removeChild
Thursday, December 17, 2009
Tuesday, June 23, 2009
Setting and Reading Cookies in Flash AS3
View actionscript 2 version of this post
Setting a cookie with Flash (Actionscript 3.0) is really easy. Reading that cookie in Flash (or passing the value of the cookie back into flash) isn't so easy (well, at least that's what the internet would have you believe). After searching for some documentation on the matter without any luck, I took matters into my own hands. It turns out if you use the jquery library, it is actually pretty easy.
First of all, you need to make sure you are using SWFobject to embed your flash, like this example: (make sure you have the swfobject js file included in your head)
<div id="flashcontent">Alt Content Goes Here</div>
<p><script type="text/javascript"> var so = new SWFObject("HomePageFlash.swf", "mymovie", "573", "434", "9", "#f0af2c");
so.addParam("quality", "high");
so.addParam("wmode", "transparent");
so.write("flashcontent");
</script></p>
Then you need jquery installed.
And you also need the jquery cookie plugin included.
ACTIONSCRIPT:
To set a cookie from flash you just need to call a js function that is in the cookie plugin thusly:
var link:URLRequest = new URLRequest("javascript:$.cookie('flash_cookie', 'loaded')");
box_mc.addEventListener(MouseEvent.CLICK, onClick);
function onClick(event:MouseEvent):void{
navigateToURL(link);
}
You can add as many params into the js call as you want thisly:
var link:URLRequest = new URLRequest("javascript:$.cookie('flash_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });");
Now for the exciting part. If you want to read that cookie in flash, all you need to do is pass it in using addVariables. In the SWFobject, just add this line of code BEFORE it writes the flash (so before the so.write part in my example):
so.addVariable("theCookie", $.cookie('flash_cookie'));
('theCookie' being a variable that will be passed into flash and the $.cookie part will pull the value of that cookie and dump it into 'theCookie')
You probably know this already, but to read that variable in AS3, you need to call it like this:
myTextBox.text = this.loaderInfo.parameters.theCookie;
(that's to display it's value in a textfield called 'myTextBox', but you can do whatever you want with it)
If you have questions, feel free to comment.
(issues: Setting cookies in flash, reading cookies with flash, passing cookies into flash, as3, actionscript3, flash CS3, flash CS4, pass cookies with addVariables, pass cookies with SWFobject)
Setting a cookie with Flash (Actionscript 3.0) is really easy. Reading that cookie in Flash (or passing the value of the cookie back into flash) isn't so easy (well, at least that's what the internet would have you believe). After searching for some documentation on the matter without any luck, I took matters into my own hands. It turns out if you use the jquery library, it is actually pretty easy.
First of all, you need to make sure you are using SWFobject to embed your flash, like this example: (make sure you have the swfobject js file included in your head)
<div id="flashcontent">Alt Content Goes Here</div>
<p><script type="text/javascript"> var so = new SWFObject("HomePageFlash.swf", "mymovie", "573", "434", "9", "#f0af2c");
so.addParam("quality", "high");
so.addParam("wmode", "transparent");
so.write("flashcontent");
</script></p>
Then you need jquery installed.
And you also need the jquery cookie plugin included.
ACTIONSCRIPT:
To set a cookie from flash you just need to call a js function that is in the cookie plugin thusly:
var link:URLRequest = new URLRequest("javascript:$.cookie('flash_cookie', 'loaded')");
box_mc.addEventListener(MouseEvent.CLICK, onClick);
function onClick(event:MouseEvent):void{
navigateToURL(link);
}
You can add as many params into the js call as you want thisly:
var link:URLRequest = new URLRequest("javascript:$.cookie('flash_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });");
Now for the exciting part. If you want to read that cookie in flash, all you need to do is pass it in using addVariables. In the SWFobject, just add this line of code BEFORE it writes the flash (so before the so.write part in my example):
so.addVariable("theCookie", $.cookie('flash_cookie'));
('theCookie' being a variable that will be passed into flash and the $.cookie part will pull the value of that cookie and dump it into 'theCookie')
You probably know this already, but to read that variable in AS3, you need to call it like this:
myTextBox.text = this.loaderInfo.parameters.theCookie;
(that's to display it's value in a textfield called 'myTextBox', but you can do whatever you want with it)
If you have questions, feel free to comment.
(issues: Setting cookies in flash, reading cookies with flash, passing cookies into flash, as3, actionscript3, flash CS3, flash CS4, pass cookies with addVariables, pass cookies with SWFobject)
Thursday, December 18, 2008
Neumont Widget
I had to make this widget for Neumont University and since it was a pretty simple app I decided to do it in AS3:
This pulls from an XML file that is on their server and rotates through news and events. You can download the files here:
[DOWNLOAD]
The xml file is in there, although you'll have to change the link in the flash if you really want it to pull from that xml because right now it is pulling the xml off Neumonts server.
Issues this covers: setTimer, new setInterval, dynamic text, XML, parsing, URLRequest, getURL, AS3, Actionscript 3.0
This pulls from an XML file that is on their server and rotates through news and events. You can download the files here:
[DOWNLOAD]
The xml file is in there, although you'll have to change the link in the flash if you really want it to pull from that xml because right now it is pulling the xml off Neumonts server.
Issues this covers: setTimer, new setInterval, dynamic text, XML, parsing, URLRequest, getURL, AS3, Actionscript 3.0
Labels:
actionscript 3.0,
AS3,
dynamic text,
new getURL,
parse,
parsing,
setInterval,
setTimer,
URLRequest,
XML
Wednesday, June 18, 2008
Loading XML and Parsing with AS3
This is what the XML doc looks like:
<images>
<pic>
<image>photos/pic17.jpg</image>
<thumb>thumbs/pic17.jpg</thumb>
<title>Kevin's Evil Face</title>
<desc>This is Kevin layin down some tracks. Boho Digitalia - February 2008</desc>
</pic>
<pic>
<image>photos/pic18.jpg</image>
<thumb>thumbs/pic18.jpg</thumb>
<title>Matt</title>
<desc>This is Matt singin some live bgv's</desc>
</pic>
<pic>
<image>photos/pic26.jpg</image>
<thumb>thumbs/pic26.jpg</thumb>
<title>The 4923</title>
<desc>Once upon a time, Matt wasn't in the band yet and Kevin played bass. Kilby Court - A Really Long Time Ago</desc>
</pic>
</images>
And this is how you load it into Flash and parse it:
var thumbs:Array = new Array();
var images:Array = new Array();
var titles:Array = new Array();
var descs:Array = new Array();
///////////////////////////////////
///// vvvvvv LOAD XML vvvvvv //////
//+++++++++++++++++++++++++++++++//
var loader:URLLoader = new URLLoader();
var xml:XML = new XML();
loader.addEventListener(Event.COMPLETE, loadXML);
loader.load(new URLRequest("images.xml"));
function loadXML(event:Event):void{
xml = new XML(event.target.data);
var total:Number = xml.pic.length();
for(var i:int = 0; i < total; i++){
thumbs[i] = xml.pic.thumb.text()[i];
images[i] = xml.pic.image.text()[i];
titles[i] = xml.pic.title.text()[i];
descs[i] = xml.pic.desc.text()[i];
}
loadThumbs();
}
//+++++++++++++++++++++++++++++++//
///////////////////////////////////
///////////////////////////////////
///// LOAD THE THUMBNAILS /////
function loadThumbs():void{
// do whatever you need here
trace(thumbs);
}
This will make 4 arrays (thumbs, images, titles, descs) and populates them with everything from your XML file. I still haven't taken the time to figure out how to parse it into a 2D array, so if anyone wants to tell me how to do it, that would rock.
<images>
<pic>
<image>photos/pic17.jpg</image>
<thumb>thumbs/pic17.jpg</thumb>
<title>Kevin's Evil Face</title>
<desc>This is Kevin layin down some tracks. Boho Digitalia - February 2008</desc>
</pic>
<pic>
<image>photos/pic18.jpg</image>
<thumb>thumbs/pic18.jpg</thumb>
<title>Matt</title>
<desc>This is Matt singin some live bgv's</desc>
</pic>
<pic>
<image>photos/pic26.jpg</image>
<thumb>thumbs/pic26.jpg</thumb>
<title>The 4923</title>
<desc>Once upon a time, Matt wasn't in the band yet and Kevin played bass. Kilby Court - A Really Long Time Ago</desc>
</pic>
</images>
And this is how you load it into Flash and parse it:
var thumbs:Array = new Array();
var images:Array = new Array();
var titles:Array = new Array();
var descs:Array = new Array();
///////////////////////////////////
///// vvvvvv LOAD XML vvvvvv //////
//+++++++++++++++++++++++++++++++//
var loader:URLLoader = new URLLoader();
var xml:XML = new XML();
loader.addEventListener(Event.COMPLETE, loadXML);
loader.load(new URLRequest("images.xml"));
function loadXML(event:Event):void{
xml = new XML(event.target.data);
var total:Number = xml.pic.length();
for(var i:int = 0; i < total; i++){
thumbs[i] = xml.pic.thumb.text()[i];
images[i] = xml.pic.image.text()[i];
titles[i] = xml.pic.title.text()[i];
descs[i] = xml.pic.desc.text()[i];
}
loadThumbs();
}
//+++++++++++++++++++++++++++++++//
///////////////////////////////////
///////////////////////////////////
///// LOAD THE THUMBNAILS /////
function loadThumbs():void{
// do whatever you need here
trace(thumbs);
}
This will make 4 arrays (thumbs, images, titles, descs) and populates them with everything from your XML file. I still haven't taken the time to figure out how to parse it into a 2D array, so if anyone wants to tell me how to do it, that would rock.
Friday, June 13, 2008
As3 Music Player
I reprogrammed the player I made for my band's website in as3. Check it out:Download Files
Somehow, and who knows how, the songs load super fast with the new sound object, which is awesome! I didn't even need to put a preloader on this one (which is good since I don't know how to make one yet). Some things about sound now are a little different but they aren't too annoying. The bar goes a little crazy when you click on it (to go to a different section in the song). It doesn't so that when I just export the swf. I'm hoping it's just some weird blogger thing.
Issues this covers: AS3, Actionscript 3.0, Sound, SoundChannel, SoundTransform, volume
Somehow, and who knows how, the songs load super fast with the new sound object, which is awesome! I didn't even need to put a preloader on this one (which is good since I don't know how to make one yet). Some things about sound now are a little different but they aren't too annoying. The bar goes a little crazy when you click on it (to go to a different section in the song). It doesn't so that when I just export the swf. I'm hoping it's just some weird blogger thing.
Issues this covers: AS3, Actionscript 3.0, Sound, SoundChannel, SoundTransform, volume
Labels:
actionscript 3.0,
AS3,
Sound,
sound object,
SoundChannel,
SoundTransform,
volume
Wednesday, June 11, 2008
Intro/Outro
This used to be a really simple task, but it's quite the ordeal in as3, but I figured it out:
View it Here
download fla's
It seems like there should be a way easier way of doing this.
Issues this covers: load movie, tween class, enter frame, target paths, variables
oh by the way, you have to do targets like this now:
MovieClip(this.parent.parent.parent).loadNextMovie(); //tell main timeline to call loadNextMovie function from loaded movie's timeline
View it Here
download fla's
It seems like there should be a way easier way of doing this.
Issues this covers: load movie, tween class, enter frame, target paths, variables
oh by the way, you have to do targets like this now:
MovieClip(this.parent.parent.parent).loadNextMovie(); //tell main timeline to call loadNextMovie function from loaded movie's timeline
Tuesday, June 10, 2008
new loadMovie
You don't need a container to load an external file anymore:
var loadMovie = new Loader();
addChild(loadMovie );
loadMovie .load(new URLRequest("page1.swf"));
but if you do want it to load into a certain movie or container, do it like this:
var loadMovie = new Loader();
container_mc.addChild(loadMovie );
loadMovie .load(new URLRequest("page1.swf"));
Apparently you can't just load a new movie in place of the new one anymore. You have to boot the old one out and then load in the new one:
container.removeChild(loadMovie);
loadMovie = new Loader();
container.addChild(loadMovie);
loadMovie.load(new URLRequest("page2.swf"));
Talking to the new movie's timeline is different too, you'll have to cast it (it's called):
MovieClip(loadMovie.content).gotoAndStop("outro");
So far the new way to load a movie is the most annoying change about as3.
var loadMovie = new Loader();
addChild(loadMovie );
loadMovie .load(new URLRequest("page1.swf"));
but if you do want it to load into a certain movie or container, do it like this:
var loadMovie = new Loader();
container_mc.addChild(loadMovie );
loadMovie .load(new URLRequest("page1.swf"));
Apparently you can't just load a new movie in place of the new one anymore. You have to boot the old one out and then load in the new one:
container.removeChild(loadMovie);
loadMovie = new Loader();
container.addChild(loadMovie);
loadMovie.load(new URLRequest("page2.swf"));
Talking to the new movie's timeline is different too, you'll have to cast it (it's called):
MovieClip(loadMovie.content).gotoAndStop("outro");
So far the new way to load a movie is the most annoying change about as3.
AS3 Tween Class
The tween class is pretty much the same as it was in AS2. When you import everything, you just have to change 'mx' to 'fl'. Also if you want to do a tween event you have to import TweenEvent:
import fl.transitions.Tween;
import fl.transitions.easing.*;
import fl.transitions.TweenEvent;
var tw1:Tween = new Tween(object,"x",Strong.easeOut,start,end,time,true);
If you want to do an event (like the old onMotionFinished), it's a little different now. You have to create an event listener like this:
tw1.addEventListener(TweenEvent.MOTION_STOP, tweenStop);
function tweenStop(event:TweenEvent):void{
var tw2:Tween = new Tween(movieclip,"x",Back.easeOut,movieclip.x,300,1,true);
}
import fl.transitions.Tween;
import fl.transitions.easing.*;
import fl.transitions.TweenEvent;
var tw1:Tween = new Tween(object,"x",Strong.easeOut,start,end,time,true);
If you want to do an event (like the old onMotionFinished), it's a little different now. You have to create an event listener like this:
tw1.addEventListener(TweenEvent.MOTION_STOP, tweenStop);
function tweenStop(event:TweenEvent):void{
var tw2:Tween = new Tween(movieclip,"x",Back.easeOut,movieclip.x,300,1,true);
}
Monday, June 9, 2008
Tweening Experiments (Enter Frame)
CODE:
var myBrain:MovieClip = new MovieClip(); //create a new empty movie clip
var xPos:Number;
var yPos:Number;
box_mc.addEventListener(Event.ENTER_FRAME, rotate); //add new enter frame, call rotate function
stage.addEventListener(MouseEvent.CLICK, moveBox); //add new mouse event, call moveBox function
function rotate(event:Event):void{
box_mc.rotation += 8; //rotate box by 8 degrees 31 times/second
}
function moveBox(event:MouseEvent):void{
xPos = mouseX; //set xPos variable
yPos = mouseY; //set yPos veriable
myBrain.addEventListener(Event.ENTER_FRAME, moveIt); //add new enter frame, call moveIt
}
function moveIt(event:Event):void{
if(Math.abs(xPos-box_mc.x)<1 && Math.abs(yPos-box_mc.y)<1){ //when the box gets real close to destination...
myBrain.removeEventListener(Event.ENTER_FRAME, moveIt); //remove the enter frame that is on myBrain
box_mc.x = xPos; //snap box into position
box_mc.y = yPos; // " " "
}else{
box_mc.x += .1 * (xPos - box_mc.x); //simple easing formula
box_mc.y += .1 * (yPos - box_mc.y); //simple easing formula
}
}
Friday, May 9, 2008
Moving Onward
Time to start learning AS3 again. This blog is going to start being FILLED with useful posts. To start it off, I'm posting this helpful as3 link:
Getting Started with ActionScript 3.0 in Adobe Flash CS3
Getting Started with ActionScript 3.0 in Adobe Flash CS3
Monday, September 17, 2007
Arrays
Arrays are the same:
var verbs:Array = ["jumped", "ran", "flew"];
//2D array:
var multiD:Array = [
["row 0 col 0","row 0 col 1"],
["row 1 col 0","row 1 col 1"],
["row 2 col 0","row 2 col 1"],
["row 3 col 0","row 3 col 1"]
];
Here is a list of Properties:
array.pop() = This method removes the last item from an array
array.push() = The push method adds a series of values to the end of an existing array
array.shift() = removes a value from the beginning of array
array.unshift() = adds a value or series of values to the beginning of your array
array.concat() = merges two arrays together ... arrayOne.concat(arrayTwo);
array.slice() = can create array with certain elements of existing array
array.sort() = will sort an array (alphabetically by default)
array.reverse() = Reverses the direction of an array.
slice() = Extracts a section of an array and returns it as a new array.
array.toString = Returns a string value representing the elements in the Array object.
var myArray:Array = new Array(); //creates a new blank array
some links to help:
http://www.kirupa.com/developer/actionscript/array2.htm
Adobe Array Help
var verbs:Array = ["jumped", "ran", "flew"];
//2D array:
var multiD:Array = [
["row 0 col 0","row 0 col 1"],
["row 1 col 0","row 1 col 1"],
["row 2 col 0","row 2 col 1"],
["row 3 col 0","row 3 col 1"]
];
Here is a list of Properties:
array.pop() = This method removes the last item from an array
array.push() = The push method adds a series of values to the end of an existing array
array.shift() = removes a value from the beginning of array
array.unshift() = adds a value or series of values to the beginning of your array
array.concat() = merges two arrays together ... arrayOne.concat(arrayTwo);
array.slice() = can create array with certain elements of existing array
array.sort() = will sort an array (alphabetically by default)
array.reverse() = Reverses the direction of an array.
slice() = Extracts a section of an array and returns it as a new array.
array.toString = Returns a string value representing the elements in the Array object.
var myArray:Array = new Array(); //creates a new blank array
some links to help:
http://www.kirupa.com/developer/actionscript/array2.htm
Adobe Array Help
Thursday, September 6, 2007
Text Fields
This is how you can create a new text field with actionscript yo (amongst other things):
var myText:TextField = new TextField(); //make a new text field
var myFormat:TextFormat = new TextFormat(); //make text format object
myFormat.font = "Verdana"; //set font
myFormat.color = 0xFF0000; //set text color
myFormat.size = 14; //set size
addChild(myText); //add it to the stage (top-left)
myText.text = "text goes in here"; //put text into it
myText.autoSize = TextFieldAutoSize.LEFT; //text will auto size from the left
myText.setTextFormat(myFormat); //You need this before you can modify proporties
Capture data from text field:
//assuming there is a button called "submit_btn" and a text field called "name_txt"
var body_txt:TextField = new TextField(); //create a text field called "body_txt"
yourName:String; //set up variable
body_txt.x = 98; //you can place text where ever
body_txt.y = 66;
submit_btn.addEventListener(mouseEvent.CLICK, onClick); //set up click mouse event
function onClick(event:MouseEvent):void{
addChild(body_txt); //place body_txt on stage (this is where user will type)
yourName = body_txt.text; //put whatever user types into yourName variable
name_txt.text = "Hi " + yourName + "!"; //put that text in the name_txt field (plus "hi")
}
Loading External Text File:
//Assume there's a field called external_txt
var externalReq:URLRequest = new URLRequest("news.txt"); //new URL Request (request file)
var externalLoad:URLLoader = new URLLoader(); //new URL Loader
externalLoad.load(externalReq); //Start Loading
externalLoad.addEventListener(Event.COMPLETE, textReady); //Listen for load completion
external_txt.wordWrap = true; //this will wrap the text
function textReady(event:Event):void{
external_txt.text = event.target.data; //places data in txt file into text field
}
Scroll Text
Assume there is a text field full of dynamic text called myText_txt. Also assume there is a button called up_btn and one called down_btn:
up_btn.addEventListener(MouseEvent.CLICK, scrollUp);
down_btn.addEventListener(MouseEvent.CLICK, scrollDown);
function scrollUp(event:MouseEvent):void{
external_txt.scrollV --; //this moves the text down
}
function scrollDown(event:MouseEvent):void{
external_txt.scrollV ++; //this moves the text up
}
var myText:TextField = new TextField(); //make a new text field
var myFormat:TextFormat = new TextFormat(); //make text format object
myFormat.font = "Verdana"; //set font
myFormat.color = 0xFF0000; //set text color
myFormat.size = 14; //set size
addChild(myText); //add it to the stage (top-left)
myText.text = "text goes in here"; //put text into it
myText.autoSize = TextFieldAutoSize.LEFT; //text will auto size from the left
myText.setTextFormat(myFormat); //You need this before you can modify proporties
Capture data from text field:
//assuming there is a button called "submit_btn" and a text field called "name_txt"
var body_txt:TextField = new TextField(); //create a text field called "body_txt"
yourName:String; //set up variable
body_txt.x = 98; //you can place text where ever
body_txt.y = 66;
submit_btn.addEventListener(mouseEvent.CLICK, onClick); //set up click mouse event
function onClick(event:MouseEvent):void{
addChild(body_txt); //place body_txt on stage (this is where user will type)
yourName = body_txt.text; //put whatever user types into yourName variable
name_txt.text = "Hi " + yourName + "!"; //put that text in the name_txt field (plus "hi")
}
Loading External Text File:
//Assume there's a field called external_txt
var externalReq:URLRequest = new URLRequest("news.txt"); //new URL Request (request file)
var externalLoad:URLLoader = new URLLoader(); //new URL Loader
externalLoad.load(externalReq); //Start Loading
externalLoad.addEventListener(Event.COMPLETE, textReady); //Listen for load completion
external_txt.wordWrap = true; //this will wrap the text
function textReady(event:Event):void{
external_txt.text = event.target.data; //places data in txt file into text field
}
Scroll Text
Assume there is a text field full of dynamic text called myText_txt. Also assume there is a button called up_btn and one called down_btn:
up_btn.addEventListener(MouseEvent.CLICK, scrollUp);
down_btn.addEventListener(MouseEvent.CLICK, scrollDown);
function scrollUp(event:MouseEvent):void{
external_txt.scrollV --; //this moves the text down
}
function scrollDown(event:MouseEvent):void{
external_txt.scrollV ++; //this moves the text up
}
Thursday, August 30, 2007
Random Numbers
Generating random number is the same as it was in AS2, but I always forget how so here are a few ways:
Math.round(Math.random() * 1000); //Gets a whole number anywhere from 0 - 1000
Math.floor(Math.random() * 10); //From 0 - 9 (cuz floor always rounds down)
Math.ceil(Math.random() * 10); //from 1 - 10 (cuz ceil always rounds up)
Math.round(Math.random() * 15) + 5; //from 5 - 20
Math.round(Math.random() * 10) - 5; //from -5 - 5
Math.round(Math.random() * 1000); //Gets a whole number anywhere from 0 - 1000
Math.floor(Math.random() * 10); //From 0 - 9 (cuz floor always rounds down)
Math.ceil(Math.random() * 10); //from 1 - 10 (cuz ceil always rounds up)
Math.round(Math.random() * 15) + 5; //from 5 - 20
Math.round(Math.random() * 10) - 5; //from -5 - 5
Tuesday, August 28, 2007
Loops and pulling movieclips out of library at runtime
Loops are pretty much the same. The only difference is that you have to put what the variable is (a number)...like this:
for(var i:Number = 0; i < 6; i++){ //you have to put "var" and that i is a number
trace(i);
}
Before if you wanted to place a bunch of movieclips on the stage at runtime using a loop, you would use attachMovie. Now you do this:
// this will pull six boxes out of the library and they will will each be placed up and to the right
var myBox:mcBox; //this creates a box variable. mcBox is what I put as the class in the movieclip properties
var myBoxX:Number = 127; //this is where the first box will be placed on the X axis
var myBoxY:Number = 271; //ditto but on the Y axis
var myBoxR:Number = 0; //start rotation at 0
for(var i:Number = 0; i < 6; i++){ //set the loop
myBox = new mcBox(); //this pulls an instance of the box mc outta the library each time the loop runs
addChild(myBox); //the new attachMovie. myBox is the variable I set above (will set 6 boxes on the stage)
myBox.x = myBoxX; //set the x position
myBox.y = myBoxY; //set y
myBox.rotation = myBoxR; //set rotation
myBoxY -= 35; //move each box up 35 pixels from the last one
myBoxX += 75; //move each 75 px over
myBoxR -= 45; //rotate each box 45 degrees clockwise
}
//Remember to click "export for actionscript" in the properties menu of the symbol in the library. In this case you have to put "mcBox" as the class name
for(var i:Number = 0; i < 6; i++){ //you have to put "var" and that i is a number
trace(i);
}
Before if you wanted to place a bunch of movieclips on the stage at runtime using a loop, you would use attachMovie. Now you do this:
// this will pull six boxes out of the library and they will will each be placed up and to the right
var myBox:mcBox; //this creates a box variable. mcBox is what I put as the class in the movieclip properties
var myBoxX:Number = 127; //this is where the first box will be placed on the X axis
var myBoxY:Number = 271; //ditto but on the Y axis
var myBoxR:Number = 0; //start rotation at 0
for(var i:Number = 0; i < 6; i++){ //set the loop
myBox = new mcBox(); //this pulls an instance of the box mc outta the library each time the loop runs
addChild(myBox); //the new attachMovie. myBox is the variable I set above (will set 6 boxes on the stage)
myBox.x = myBoxX; //set the x position
myBox.y = myBoxY; //set y
myBox.rotation = myBoxR; //set rotation
myBoxY -= 35; //move each box up 35 pixels from the last one
myBoxX += 75; //move each 75 px over
myBoxR -= 45; //rotate each box 45 degrees clockwise
}
//Remember to click "export for actionscript" in the properties menu of the symbol in the library. In this case you have to put "mcBox" as the class name
Conditions
Conditions in AS3 are exactly the same as they were previously (woo hoo!) All the operators are the same, you can nest conditions, you can have compound condtions and so forth. Here is an example of one:
check_mc.addEventListener(MouseEvent.CLICK, onClick); //add mouse event, call onClick function
function onClick(event:MouseEvent):void{ //define onClick function
if(box1_mc.rotation == box2_mc.rotation || box1_mc.alpha == box2_mc.alpha){ //if rotation is the same OR alpha is the same..
trace("condition is true");
}else{ //if not...
trace("condition is false");
}
}
check_mc.buttonMode = true; //set check_mc as a button/show hand cursor
check_mc.addEventListener(MouseEvent.CLICK, onClick); //add mouse event, call onClick function
function onClick(event:MouseEvent):void{ //define onClick function
if(box1_mc.rotation == box2_mc.rotation || box1_mc.alpha == box2_mc.alpha){ //if rotation is the same OR alpha is the same..
trace("condition is true");
}else{ //if not...
trace("condition is false");
}
}
check_mc.buttonMode = true; //set check_mc as a button/show hand cursor
Sunday, August 19, 2007
Classes
Actionscript 3 is super class based, which is cool because classes are extremely powerful, and I've never really used them before. Now I have to learn how to use them. Classes are awesome cuz you can make one and use it over and over again. Here are some examples of simple simple classes:
You can download all the files here: [download]
HERE IS HOW THE CODE IS SET UP FOR A SIMPLE CLASS:
This code needs to be in a seperate .as file
whatever you save this file as is what your CLASS NAME will be
/// this class adds to the built in movie clip class ///
package{
import flash.display.MovieClip; //Imports movie clip class
import flash.events.MouseEvent; //Imports the mouse event
public class FunButton extends MovieClip{
private var _origXScale:Number; //create a variable to remember the original size of movie clip
private var _origYScale:Number; //ditto
public function FunButton(){
_origXScale = this.scaleX; //set x scale variable
_origYScale = this.scaleY; //set y scale variable
this.addEventListener(MouseEvent.ROLL_OVER, grow); //add listener. call function "grow"
this.addEventListener(MouseEvent.ROLL_OUT, shrink); //add listener. call function "shrink"
}
private function grow(event:MouseEvent):void{
this.scaleX *= 1.5; //this is make the mc grow to 150% its size (width)
this.scaleY *= 1.5; //this is make the mc grow to 150% its size (height)
}
private function shrink(event:MouseEvent):void{
this.scaleX = _origXScale; //go back to normal
this.scaleY = _origYScale; //go back to normal
}
}
}
now if you have a movieclip in an fla file, right click on it in the library and go to "linkage" and in the class field type in the CLASS NAME (whatever you named your .as file) and all instances of that movieclip will have those proporties. This is the very very very tip of the iceburg of what classes can do.
You can download all the files here: [download]
HERE IS HOW THE CODE IS SET UP FOR A SIMPLE CLASS:
This code needs to be in a seperate .as file
whatever you save this file as is what your CLASS NAME will be
/// this class adds to the built in movie clip class ///
package{
import flash.display.MovieClip; //Imports movie clip class
import flash.events.MouseEvent; //Imports the mouse event
public class FunButton extends MovieClip{
private var _origXScale:Number; //create a variable to remember the original size of movie clip
private var _origYScale:Number; //ditto
public function FunButton(){
_origXScale = this.scaleX; //set x scale variable
_origYScale = this.scaleY; //set y scale variable
this.addEventListener(MouseEvent.ROLL_OVER, grow); //add listener. call function "grow"
this.addEventListener(MouseEvent.ROLL_OUT, shrink); //add listener. call function "shrink"
}
private function grow(event:MouseEvent):void{
this.scaleX *= 1.5; //this is make the mc grow to 150% its size (width)
this.scaleY *= 1.5; //this is make the mc grow to 150% its size (height)
}
private function shrink(event:MouseEvent):void{
this.scaleX = _origXScale; //go back to normal
this.scaleY = _origYScale; //go back to normal
}
}
}
now if you have a movieclip in an fla file, right click on it in the library and go to "linkage" and in the class field type in the CLASS NAME (whatever you named your .as file) and all instances of that movieclip will have those proporties. This is the very very very tip of the iceburg of what classes can do.
Events
Events are WAY different than they used to be. Here's a quick rundown:
MOUSE EVENTS:
You now have to create a listener whenever you have a mouse event. Here is an example:
box_mc.addEventListener(MouseEvent.CLICK, onClick); //add click event and tell it to call onClick function
box_mc.addEventListener(MouseEvent.ROLL_OVER, boxOver); //rollover event, call boxOver function
box_mc.addEventListener(MouseEvent.ROLL_OUT, boxOut); //rollout even, call function called boxOver
function boxOver(event:MouseEvent):void{
event.target.alpha = .5;
}
function boxOut(event:MouseEvent):void{
event.target.alpha = 1;
}
function onClick(event:MouseEvent):void{
//trace("you've been clicked");
event.target.y -= 15;
event.target.rotation += 45;
}
box_mc.buttonMode = true; //this tells box_mc to be a button and show the hand cursor
KEYBOARD EVENTS:
stage.addEventListener(KeyboardEvent.KEY_DOWN, jump); //add listener just like the mouse events (key down)
stage.addEventListener(KeyboardEvent.KEY_UP, land); //key up listener
function jump(event:KeyboardEvent):void{
//trace(event.keyCode);
box_mc.y -= 50;
stage.removeEventListener(KeyboardEvent.KEY_DOWN, jump); //this will delete the key down listener when you push a key
stage.addEventListener(Event.ENTER_FRAME, flip); //this is the new enterframe event (this will call flip function)
}
function land(event:KeyboardEvent):void{
box_mc.y += 50;
stage.addEventListener(KeyboardEvent.KEY_DOWN, jump); //this creates a new key down listener when you release a key
stage.removeEventListener(Event.ENTER_FRAME, flip); //this removes the enterframe event when you release a key
}
function flip(event:Event):void{
box_mc.rotation += 45; //constantly rotates the box 45 degrees
box_mc.x += 10; //constantly moves the box 10 pixels to the right
}
LINK TO WEBSITE:
var link:URLRequest = new URLRequest("http://www.google.com"); //make the request
box_mc.addEventListener(MouseEvent.CLICK, onClick); //create the click listener, call function called onClick
function onClick(event:MouseEvent):void{
navigateToURL(link); //this will send the browser to the url specified above
}
box_mc.buttonMode = true; //make the movieclip a button
TIMER EVENT:
this is like the new setInterval
var jumpTimer:Timer = new Timer(5000, 10); //first peramiter is how often, second is how many times
jumpTimer.addEventListener(TimerEvent.TIMER, jump); //sets a listener to the jumpTimer timer, call function "jump"
function jump(event:TimerEvent):void{
animation_mc.play();
}
jumpTimer.start(); //this starts the timer DUH
MOUSE EVENTS:
You now have to create a listener whenever you have a mouse event. Here is an example:
box_mc.addEventListener(MouseEvent.CLICK, onClick); //add click event and tell it to call onClick function
box_mc.addEventListener(MouseEvent.ROLL_OVER, boxOver); //rollover event, call boxOver function
box_mc.addEventListener(MouseEvent.ROLL_OUT, boxOut); //rollout even, call function called boxOver
function boxOver(event:MouseEvent):void{
event.target.alpha = .5;
}
function boxOut(event:MouseEvent):void{
event.target.alpha = 1;
}
function onClick(event:MouseEvent):void{
//trace("you've been clicked");
event.target.y -= 15;
event.target.rotation += 45;
}
box_mc.buttonMode = true; //this tells box_mc to be a button and show the hand cursor
KEYBOARD EVENTS:
stage.addEventListener(KeyboardEvent.KEY_DOWN, jump); //add listener just like the mouse events (key down)
stage.addEventListener(KeyboardEvent.KEY_UP, land); //key up listener
function jump(event:KeyboardEvent):void{
//trace(event.keyCode);
box_mc.y -= 50;
stage.removeEventListener(KeyboardEvent.KEY_DOWN, jump); //this will delete the key down listener when you push a key
stage.addEventListener(Event.ENTER_FRAME, flip); //this is the new enterframe event (this will call flip function)
}
function land(event:KeyboardEvent):void{
box_mc.y += 50;
stage.addEventListener(KeyboardEvent.KEY_DOWN, jump); //this creates a new key down listener when you release a key
stage.removeEventListener(Event.ENTER_FRAME, flip); //this removes the enterframe event when you release a key
}
function flip(event:Event):void{
box_mc.rotation += 45; //constantly rotates the box 45 degrees
box_mc.x += 10; //constantly moves the box 10 pixels to the right
}
LINK TO WEBSITE:
var link:URLRequest = new URLRequest("http://www.google.com"); //make the request
box_mc.addEventListener(MouseEvent.CLICK, onClick); //create the click listener, call function called onClick
function onClick(event:MouseEvent):void{
navigateToURL(link); //this will send the browser to the url specified above
}
box_mc.buttonMode = true; //make the movieclip a button
TIMER EVENT:
this is like the new setInterval
var jumpTimer:Timer = new Timer(5000, 10); //first peramiter is how often, second is how many times
jumpTimer.addEventListener(TimerEvent.TIMER, jump); //sets a listener to the jumpTimer timer, call function "jump"
function jump(event:TimerEvent):void{
animation_mc.play();
}
jumpTimer.start(); //this starts the timer DUH
Functions
Functions in as3 are pretty much the same as they were in as2. Before you had the option of returning a value from the function and defining what was going to be returned. Now you HAVE to tell flash what is going to be returned, even if nothing is going to be.
If you're going to return a number, this is how you do it:
function moveBox():Number{
box1_mc.y -= 100;
box1_mc.rotation += 45;
box1_mc.scaleX = 2;
box1_mc.scaleY = 2;
return box1_mc.y;
}
If you're not going to return anything, this is how you do it
function moveBox():void{
box1_mc.y -= 100;
box1_mc.rotation += 45;
box1_mc.scaleX = 2;
box1_mc.scaleY = 2;
}
If you're going to return a number, this is how you do it:
function moveBox():Number{
box1_mc.y -= 100;
box1_mc.rotation += 45;
box1_mc.scaleX = 2;
box1_mc.scaleY = 2;
return box1_mc.y;
}
If you're not going to return anything, this is how you do it
function moveBox():void{
box1_mc.y -= 100;
box1_mc.rotation += 45;
box1_mc.scaleX = 2;
box1_mc.scaleY = 2;
}
Movieclip Proporties
Movie clip proporties no longer include a _ anymore. Before when it would be box_mc._x it is now box_mc.x. Also, the scale proporty has changed all together. One more thing, for anything that has a percentage (like alpha or scale) you need to put it in a decimal point. alpha = 50 is now alpha =.5 and so forth. Here is a list of some common proporties:
movieclip_mc.alpha = .5;
movieclip_mc.rotation = 0;
movieclip_mc.x = 100;
movieclip_mc.y = 100;
movieclip_mc.scaleY = 1.5;
movieclip_mc.scaleX = 1.5;
movieclip_mc.width = 280;
movieclip_mc.height = 10;
movieclip_mc.alpha = .5;
movieclip_mc.rotation = 0;
movieclip_mc.x = 100;
movieclip_mc.y = 100;
movieclip_mc.scaleY = 1.5;
movieclip_mc.scaleX = 1.5;
movieclip_mc.width = 280;
movieclip_mc.height = 10;
Variables
In as 3, you have to tell flash what you're going to put into a variable. For example:
var userName:String = "Nate";
var userAge:Number = 25;
var myArray:Array = ["a","b","c","d"];
var theToggle:Boolean = true;
var whatever:*; //You can pass anything into that variable
You also HAVE to put the "var" on there. That wasn't required before, but now it is.
var userName:String = "Nate";
var userAge:Number = 25;
var myArray:Array = ["a","b","c","d"];
var theToggle:Boolean = true;
var whatever:*; //You can pass anything into that variable
You also HAVE to put the "var" on there. That wasn't required before, but now it is.
Subscribe to:
Posts (Atom)