Archive for May, 2009
Dynamic Slide Show AS3 Complete Guide.
by admin on May.30, 2009, under Tutorials
This complete new tutorial is still in the process of being created. A few sections are already available with files to download, so be patient and don’t hesitate to already comment on the available sections or make requests for the incoming ones.
A Dynamic Slide Show is quite a simple application but the more dynamic you want it, the more complex it gets. This tutorial will show you how to create a dynamic, flexible, and versatile slide show with AS3. The tutorial is divided in sections, each section covering a particular subject in the creation of a Slide Show. The sections are as follow:
1. Loading data (or why everybody uses XML?)
2. Loading Pictures (or How do I time this?)
3. Resizing and Autoresizing (or can the swf resizes itself?)
4. Adding Setup Options (or letting the user take charge)
5. Adding Effects and Create Custom Effects (or Put The BitmapData Class to Work)
6. Randomizing (or Adding Some Life)
7. Adding Texts (or The Advantage of Classes)
8. Adding Sound (or Turn That Off!)
9. Cleaning Up (or Learn How To Take The Trash Out)
10. CMS (or Live And Let Live)
Each new section will build upon the preceding one. The code will be presented in a document class format running in Flash CS3/4 making it easily adaptable for Flex users (might need to import some missing classes and set some additional stage properties). So let’s already start with our first section.
Loading data (or why everybody uses XML?).
Most application must load some kind of data when they start and a Dynamic Slide Show is not different, it must load at least the path of the pictures it’s going to display and maybe additional information like timing, URL paths and so on. This first section shows you how to load data via an XML object.
Why everybody uses XML?
XML as become a standard on the web for passing information from website to website, from web application to server side and reverse, and in many other cases. The reason is simple, with XML the data is (or is supposed to be) well organized, already sorted for you. XML nodes are supposed to describe the data they enclose making the work of the programmer easier.
So let’s start building our slide show, create a new Actionscript 3 document, set its width and height to 400, its frame rate to 30 and save. Now let’s create our document class, create a new Actionscript file and save it in the same folder than the Fla file you just created, give it for example a name of “LoadingData.as”. Now back to our Fla file, set the document class as “LoadingData” and save. From now we will be working with the document class only but leave the Fla open anyway as we will need it for compiling the swf. Let’s create a simple XML that we will load in our application:
<SLIDE_SHOW>
<PICTURES>
<PICTURE_PATH></PICTURE_PATH>
<PICTURE_PATH></PICTURE_PATH>
<PICTURE_PATH></PICTURE_PATH>
<PICTURE_PATH></PICTURE_PATH>
</PICTURES>
</SLIDE_SHOW>
SLIDE_SHOW is what we call a root tag, it encloses all the other tags and is required to form a valid XML object. PICTURES is the tag that we will use to pass our picture paths to the application, this tag will enclose all the picture paths. PICTURE_PATH is our final tag and we will add paths inside these tags to point to our pictures. We still did not setup a picture folder but let’s go ahead and pretend we did and add some paths into our XML:
<SLIDE_SHOW>
<PICTURES>
<PICTURE_PATH>mypicture1.jpg</PICTURE_PATH>
<PICTURE_PATH>mypicture2.jpg</PICTURE_PATH>
<PICTURE_PATH>mypicture3.jpg</PICTURE_PATH>
<PICTURE_PATH>mypicture4.jpg</PICTURE_PATH>
</PICTURES>
</SLIDE_SHOW>
Here now there’s something in our tags, let’s save this XML as “slide_show.xml” and save it in the same folder as our Fla and as files.
Now let’s write our document class. Open the actionscript file named “LoadingData.as”. A document class in AS3 must be enclosed in a package so let’s do that first:
package{
}
Quite easy, now inside this package let’s declare our document class (its name must match the actionscript file name):
package {
public class LoadingData
{
}
}
A document class in AS3 must extend either MovieClip or Sprite, use MovieClip when you intend to use timeline based animation, use Sprite when you won’t use any timeline. We won’t use any timeline based animation here so let’s go ahead and extend Sprite. We import the Sprite class and extends it:
package {
import flash.display.Sprite;
public class LoadingData extends Sprite
{
}
}
Finaly let’s create our constructor. A constructor is a function with the same name as the class, it never returns a value and will automatically run when the document class is called (when the application starts):
package {
import flash.display.Sprite;
public class LoadingData extends Sprite
{
public function LoadingData()
{
}
}
}
I will not describe again how to create a document class in the next sections so if you forget how to do this come back to this page and review the process. Now time to write code that actually does something! Loading our XML! We need to import a couple of classes to load our data, the URLRequest class, all the events class package (we’ll need those) events.*, the TextField class that we’ll use to show our XML, and the URLLoader class. We also declare a few member variables: A variable to hold our XML data “var picture_xml:XML;”, a variable to hold our URLRequest “var url_request:URLRequest;”, and a variable to hold our URLLoader “var url_loader:URLLoader;”:
package {
import flash.display.Sprite;
import flash.net.URLRequest;
import flash.net.URLLoader;
public class LoadingData extends Sprite
{
var picture_xml:XML
var url_request:URLRequest;
var url_loader:URLLoader;
public function LoadingData()
{
}
}
}
Now in our constructor we are going to instantiate our URLRequest, and URLLoader variables, write some code to initiate the loading and add a COMPLETE event to trigger a function when the XML data is fully loaded:
package {
import flash.display.Sprite;
import flash.net.URLRequest;
import flash.net.URLLoader;
import flash.events.*;
import flash.text.TextField;
public class LoadingData extends Sprite
{
var picture_xml:XML
var url_request:URLRequest;
var url_loader:URLLoader;
public function LoadingData()
{
url_request = new URLRequest("slide_show.xml");
url_loader = new URLLoader();
url_loader.addEventListener(Event.COMPLETE, completeHandler);
url_loader.load(url_request);
}
private function completeHandler(e:Event):void{
picture_xml = new XML(url_loader.data);
var txt:TextField = new TextField();
txt.width = stage.stageWidth;
txt.height = stage.stageHeight;
txt.wordWrap = true;
txt.text = picture_xml;
addChild(txt);
}
}
}
If everything went well you should like me see our XML displayed in our textfield. Now to be truly dynamic our slide show should be able to load different XMLs. For example you should be able to display two slide shows in the same html page with different pictures which means loading different XMLs. We can do so by using FlashVars. Back to our Fla file you can go ahead and hit “publish” to get an html file with the slide show embedded. Now we can modify this html and add FlashVars to pass to our slide show. Open the html file in your favorite html editor or notepad and look for this:
<script language="JavaScript" type="text/javascript">
AC_FL_RunContent(
'codebase', 'http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=10,0,0,0',
'width', '400',
'height', '400',
'src', 'loading',
'quality', 'high',
'pluginspage', 'http://www.adobe.com/go/getflashplayer',
'align', 'middle',
'play', 'true',
'loop', 'true',
'scale', 'showall',
'wmode', 'window',
'devicefont', 'false',
'id', 'loading',
'bgcolor', '#ffffff',
'name', 'loading',
'menu', 'true',
'allowFullScreen', 'false',
'allowScriptAccess','sameDomain',
'movie', 'loading',
'salign', ''
); //end AC code
add between two lines this ‘FlashVars’, ‘xml=slide_show.xml’, so you should now have this:
<script language="JavaScript" type="text/javascript">
AC_FL_RunContent(
'codebase', 'http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=10,0,0,0',
'width', '400',
'height', '400',
'src', 'loading',
'quality', 'high',
'pluginspage', 'http://www.adobe.com/go/getflashplayer',
'align', 'middle',
'play', 'true',
'loop', 'true',
'scale', 'showall',
'wmode', 'window',
'devicefont', 'false',
'id', 'loading',
'bgcolor', '#ffffff',
'name', 'loading',
'menu', 'true',
'allowFullScreen', 'false',
'allowScriptAccess','sameDomain',
'FlashVars', 'xml=slide_show.xml',
'movie', 'loading',
'salign', ''
); //end AC code
Now look for this:
<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=10,0,0,0" width="400" height="400" id="loading" align="middle">
<param name="allowScriptAccess" value="sameDomain" />
<param name="allowFullScreen" value="false" />
<param name="movie" value="loading.swf" /><param name="quality" value="high" /><param name="bgcolor" value="#ffffff" /> <embed src="loading.swf" quality="high" bgcolor="#ffffff" width="400" height="400"name="loading" align="middle" allowScriptAccess="sameDomain" allowFullScreen="false" type="application/x-shockwave-flash" pluginspage="http://www.adobe.com/go/getflashplayer" />
</object>
and add FlashVars at two places like this:
<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=10,0,0,0" width="400" height="400" id="loading" align="middle">
<param name="allowScriptAccess" value="sameDomain" />
<param name="allowFullScreen" value="false" />
<param name="FlashVars" value="xml=slide_show.xml">
<param name="movie" value="loading.swf" /><param name="quality" value="high" /><param name="bgcolor" value="#ffffff" /> <embed src="loading.swf" quality="high" bgcolor="#ffffff" width="400" height="400" FlashVars=”xml=slide_show.xml” name=”loading” align=”middle” allowScriptAccess=”sameDomain” allowFullScreen=”false” type=”application/x-shockwave-flash” pluginspage=”http://www.adobe.com/go/getflashplayer” />
</object>
Now let’s modify our document class to load our FlashVars prior to load our XML, we do this in the constructor:
var xml_path:String = "";
xml_path = this.loaderInfo.parameters.xml || "slide_show.xml";
url_request = new URLRequest(xml_path);
Now if you compile the application and run it in a browser you should be able to see our xml data and you should be able to pass different XMLs too. A little explanation about his line:
xml_path = this.loaderInfo.parameters.xml || "slide_show.xml";
This is a conditional that will allow us to keep developing our application in Flash CS3/4 since FlashVars is available only in a browser. The conditional first passes the FlashVars to the string variable and if the value is not available it then passes the string path which is the one we’ll use for developing. Now let’s go even further and load instead of an XML file, an XML object.
An XML object is not an XML file, an XML object is any valid XML formatted document or string that can be interpreted as XML. So another way to load XML data is to use a server side script like this PHP one called “simple.php”:
<?
$xml = "<SLIDE_SHOW><PICTURES><PICTURE_PATH>mypicture1.jpg</PICTURE_PATH><PICTURE_PATH>mypicture2.jpg</PICTURE_PATH>";
$xml .= "<PICTURE_PATH>mypicture3.jpg</PICTURE_PATH><PICTURE_PATH>mypicture4.jpg</PICTURE_PATH></PICTURES></SLIDE_SHOW>";
print($xml);
?>
Now we can modify the FlashVars to pass this “simple.php” instead of an XML file. Let’s do that and upload everything to a PHP enabled server and test it. If everything went well you should like me see our data. Now let’s go further in the server side script interaction, we could use our server side script to look inside a folder and pass as an XML object any picture we find, so let’s set up a folder with a few pictures on the server and create a new PHP script to grab any pictures it can find, this script is called “external.php” don’t forget to change the FlashVars when testing this:
<?php
$dir = opendir("assets/");
print("<SLIDE_SHOW><PICTURES>");
while($file = readdir($dir)){
if((substr(strtolower($file),-4)==".png") || (substr(strtolower($file),-4)==".jpg") || (substr(strtolower($file),-4)==".gif") ||
(substr(strtolower($file),-5)==".jpeg")){
print("<PICTURE_PATH>assets/".$file."</PICTURE_PATH>");
}
}
print("</PICTURES></SLIDE_SHOW>");
?>
When you test this you get back an XMLobject with all pictures present in a given folder. We can also apply the same principle with a database, we could create a database to save the picture paths and give each picture a type so our php script will give us the right pictures for the right slide show. For example if there’s a slide show on an index page then we could have pictures in the database with the type “index” and for another slide show on the about page we could have type ‘about’. Let’s see this in action with this new PHP script called “database.php” and let’s pass the picture type directly as a query with the PHP script name like this:
xml=database.php?type=index
and here is the script:
<?php
$db = mysql_connect("yourid", "yourusername" , "yourpassword");
mysql_select_db("yourdatabase",$db);
$query = 'select PICTURE_PATH from PICTURES where TYPE='.$_REQUEST['type'].’ ‘;
$query_result = mysql_query($query);
print(”<SLIDE_SHOW><PICTURES>”);
while ($row = mysql_fetch_array($query_result, MYSQL_ASSOC)) {
print(”<PICTURE_PATH>”.$row['PICTURE_PATH'].”</PICTURE_PATH>”);
}
print(”</PICTURES></SLIDE_SHOW>”);
?>
As you saw loading data is a bigger subject than one might think, anyway we covered the most standard situations with the database loading being the most flexible in my opinion since we’ll be able to link this easily to a CMS (sure why not?). Now it’s time to laod some pictures!
Drawing shapes with AS3
by admin on May.30, 2009, under Tutorials
Drawing any shapes with AS3 is very easy. In this tutorial I will show you how to draw a basic shape and then how to apply this knowledge into a dynamic application.
1. Open your Flash CS3 software, select “new”, “Flash File (Actionscript 3) “, click “Ok”, then go to “Modify”, “Document”, enter 300 for the width and height and enter 30 for the frame rate.
2. Open the “Actions” panel.
3. Copy and Paste this code:
var square:Sprite = new Sprite();
addChild(square);
square.graphics.lineStyle(3,0x00ff00);
square.graphics.beginFill(0x0000FF);
square.graphics.drawRect(0,0,100,100);
square.graphics.endFill();
square.x = stage.stageWidth/2-square.width/2;
square.y = stage.stageHeight/2-square.height/2;
4. Hit “Ctrl+Enter” or go to “Control”, “Test Movie” to test our Flash movie. You should see this:
Here is what the code does:
var square:Sprite = new Sprite();
We create a sprite object which is pretty much like a MovieClip but without a timeline.
addChild(square);
We add our sprite to the display list which means we tell Flash that we want this sprite to be displayed.
square.graphics.lineStyle(3,0x00ff00);
We assign a graphics object to our sprite (If you worked with Java that might seem pretty familiar). Then we assign a line style to the graphic object.
square.graphics.beginFill(0x0000FF);
We assign a fill color to our graphic object.
square.graphics.drawRect(0,0,100,100);
We draw a rectangle using the drawRect() method.
square.graphics.endFill();
We tell Flash we are done drawing. (the other two lines of code are for positioning).
Now since there are many platforms and many ways to write AS3 code, I’m going to try to make this tutorial as versatile as possible so here is a document class version that you can use with a Flex Actionscript project or simply by using the document class box in the Flash CS3 environment. So copy and paste the following code in Notepad for example and save it as simple_shape.as:
package{
import flash.display.Sprite;
public class simple_shape extends Sprite{
var square:Sprite;
public function simple_shape(){
square = new Sprite();
addChild(square);
square.graphics.lineStyle(3,0x00ff00);
square.graphics.beginFill(0x0000FF);
square.graphics.drawRect(0,0,100,100);
square.graphics.endFill();
square.x = stage.stageWidth/2-square.width/2;
square.y = stage.stageHeight/2-square.height/2;
}}
}
Now in Flex, set this file as the document class, and in Flash CS3 write “simple_shape” in the document class box. Run the example.
Now starting from a document class, it’s easy enough to create a real class out of it so I’ll leave that up to you.
We can as easily create a rounded rectangle:
var square:Sprite = new Sprite();
addChild(square);
square.graphics.lineStyle(3,0x00ff00);
square.graphics.beginFill(0x0000FF);
square.graphics.drawRoundRect(0,0,100,100,20);
square.graphics.endFill();
square.x = stage.stageWidth/2-square.width/2;
square.y = stage.stageHeight/2-square.height/2;
Document Class (simple_rounded_shape.as):
package{
import flash.display.Sprite;
public class simple_rounded_shape extends Sprite{
var square:Sprite;
public function simple_rounded_shape(){
square = new Sprite();
addChild(square);
square.graphics.lineStyle(3,0x00ff00);
square.graphics.beginFill(0x0000FF);
square.graphics.drawRoundRect(0,0,100,100,20);
square.graphics.endFill();
square.x = stage.stageWidth/2-square.width/2;
square.y = stage.stageHeight/2-square.height/2;
}}
}
And here is the result:
You can of course get a total control on how the shape is drawn with the good old moveTo() and lineTo() methods:
var square:Sprite = new Sprite();
addChild(square);
square.graphics.lineStyle(3,0x00ff00);
square.graphics.beginFill(0x0000FF);
drawShape(square);
square.graphics.endFill();
square.x = stage.stageWidth/2-square.width/2;
square.y = stage.stageHeight/2-square.height/2;
function drawShape(sprite:Sprite):void{
sprite.graphics.lineStyle(3,0x00ff00);
sprite.graphics.beginFill(0x0000FF);
sprite.graphics.moveTo(0,0);
sprite.graphics.lineTo(100,0);
sprite.graphics.lineTo(100,100);
sprite.graphics.lineTo(0,100);
sprite.graphics.lineTo(0,0);
sprite.graphics.endFill();
}
Document Class (simple_lineTo_shape.as):
package{
import flash.display.Sprite;
public class simple_lineTo_shape extends Sprite{
var square:Sprite;
public function simple_lineTo_shape(){
square = new Sprite();
addChild(square);
square.graphics.lineStyle(3,0x00ff00);
square.graphics.beginFill(0x0000FF);
drawShape(square);
square.graphics.endFill();
square.x = stage.stageWidth/2-square.width/2;
square.y = stage.stageHeight/2-square.height/2;
}
private function drawShape(sprite:Sprite):void{
sprite.graphics.lineStyle(3,0x00ff00);
sprite.graphics.beginFill(0x0000FF);
sprite.graphics.moveTo(0,0);
sprite.graphics.lineTo(100,0);
sprite.graphics.lineTo(100,100);
sprite.graphics.lineTo(0,100);
sprite.graphics.lineTo(0,0);
sprite.graphics.endFill();
}}
}
MoveTo() and lineTo() methods were already part of AS2 and I covered how to use them in details in this AS2 tutorial. These are actually the methods that we will need most of the time if we want to create a dynamic shape. Let’s see that in the next page.
Introduction to Pixel Bender and Shader for Flash Player 10
by admin on May.30, 2009, under Tutorials
Flash Player 10 came with a set of new classes to load and use Pixel Bender files in our Flash applications. In this tutorial we’ll take a look at Pixel bender syntax and how to write your own Pixel Bender files. We will also see how to load Pixel Bender files in Flash and use them in different ways.
First if you still did not download the Pixel Bender Toolkit you should do so here. The Pixel Bender Toolkit comes with a set of Pixel Bender filters so feel free to study them to get a better understanding of Pixel Bender syntax. You can also search the web to find additional Pixel Bender filters.
In this tutorial we’ll create some simple filters with the Pixel Bender Toolkit and later on we’ll use some existing ones so let’s get started.
Start the Pixel Bender toolkit and choose “New Kernel”, a complete new working kernel file is automatically created for you. You can already run this filter, you’ll probably be prompted to load a picture and after doing so, the filter will be running. Of course the only thing this filter is doing so far is copy each pixels from the base image into the output image so that’s not that useful but let’s take a look anyway. First you have the kernel description:
kernel NewFilter
<
namespace : "Your Namespace";
vendor : "Your Vendor";
version : 1;
description : "your description";
>
You can give a name to your filter here as well as other information like the version of this filter, a description and so on. Next:
input image4 src;
output pixel4 dst;
You specify an input of type image4 (4 channels) and a name “src”. The filter will use this input as a base. You also specify an output of type pixel4 (4 channels) and a name “dst”. The filter will pass the result of its calculation to this ouput. Then:
void evaluatePixel(){
dst = sampleNearest(src,outCoord());
}
This function (evaluatePixel) will run once for each element (pixel) in your input data. The sampleNearest method is returning a pixel value and this pixel value is assigned to the “dst” output. The sampleNearest method takes a source (in our case an image4 source), and a set of coordinate (outCoord() returns the coordinates of the current element or pixel). If you pass an image4 you get back a pixel4 value, if you were to pass an image3, you would get a pixel3 and so on. The number determines how many values you get or have to set for example:
float myfloat = 1.0;//one value
float2 myotherfoat = float2(1.0,1.0);//two values
float3 mythreefoat = float3(1.0,1.0,1.0);//three values
float4 myfourfoat = float4(1.0,1.0,1.0,1.0);//four values
Casting is possible of course if type are compatible like from int to float for example. Obviously if you try to pass a pixel 3 to an image4 you’ll get yourself an error so just be aware of that. Let’s modify our code so our output looks different:
dst = pixel4(sin(float4(sampleNearest(src,outCoord()))));
You should get a slight alteration of your picture lightness. You probably know the sin method already and what it does. Here we casted our sampleNearest result into a float4 (so we did cast from pixel4 to float4) so we could apply the sin method, then of course we did cast back to pixel4 so we could assign the result into our output. Already you can experiment with the numerous math methods and see what result you get. try this one for example:
dst = pixel4(sqrt(float4(sampleNearest(src,outCoord()))));
Moreover we could separate each pixels and apply some calculation on each one of them:
pixel4 temp = sampleNearest(src,outCoord());
dst = temp;
Back to the beginning but here we have our pixels stored in a variable so we can access them individually so let’s do that now:
pixel4 temp = sampleNearest(src,outCoord());
temp.r = 0.0;
dst = temp;
Here we basically turned off the red channel so all red is gone from our picture. You could apply numerous math operation on these pixels and get some amazing result. Of course your level in math will determine your ability to create complex filters but this is for you to discover. Now it’s time to take a look at what we can do with Pixel Bender filters in Flash and as we go we’ll look at more Pixel Bender code of course.
Reflection effect with AS2 in 4 easy steps
by admin on May.29, 2009, under Tutorials
A discreet reflection effect can add a nice “touch” when displaying pictures, graphics and such. In this tutorial you will learn not only how to create this effect but also how it works and how to modify it as you please, so let’s get started!
Open your Flash software, select “new”, “Flash document”, click “Ok”, then go to “Modify”, “Document”, enter 400 for the width and heigth and enter 30 for the frame rate.
Open the “Actions” panel.
First Step:
Of course to apply a reflection we first need a picture or graphic to apply the reflection to.
In this first step we just load dynamically a picture:
this.createEmptyMovieClip("image_mc", 1);
var mclListener:Object = new Object();
mclListener.onLoadInit = function(target_mc:MovieClip) {
target_mc._x = (Stage.width/2)-(target_mc._width/2);
target_mc._y = 0;
};
var image_mcl:MovieClipLoader = new MovieClipLoader();
image_mcl.addListener(mclListener);
image_mcl.loadClip("none.jpg", image_mc);//replace this by any picture you have
Hit “Ctrl+Enter” or go to “Control”, “Test Movie” to test our Flash movie. You should see this:
That’s a nice looking picture. Here is what the code does:
this.createEmptyMovieClip("image_mc", 1);
We create a movieclip and give it a name of “image_mc” and a depth of 1.
var mclListener:Object = new Object();
We create a object that we will use to check (listening) if the picture is loaded.
mclListener.onLoadInit = function(target_mc:MovieClip) {
target_mc._x = (Stage.width/2)-(target_mc._width/2);
target_mc._y = 0;
};
When the picture is fully loaded the onLoadInit function will trigger and set the referenced movieclip (image_mc) to the middle of the screen horizontally.
var image_mcl:MovieClipLoader = new MovieClipLoader();
image_mcl.addListener(mclListener);
image_mcl.loadClip("none.jpg", image_mc);//replace this by any picture you have
We create a MovieClipLoader object, then set our listener object, then load the picture in the image_mc. Note: replace “none.jpg” by any picture you want, be aware that this code does not re size pictures.
Step Two:
To create the reflection effect we need to copy the existing movieclip, flip the image and place it below the existing movieclip. To do this, we are going to create a custom function, pass the existing movieclip as parameter and call the function from within the onLoadInit function we already used. In this new function we will use the bitmapData class to copy our existing movieclip so first we need to import the bitmapData class.
Before any other code, insert this to import the bitmapData class:
import flash.display.BitmapData;
inside the onLoadInit function insert this new line:
mclListener.onLoadInit = function(target_mc:MovieClip) {
target_mc._x = (Stage.width/2)-(target_mc._width/2);
target_mc._y = 0;
reflect(target_mc);// new line used to call our new function
};
Now time to create our new function:
function reflect(target_mc:MovieClip):Void{
var myBitmapData:BitmapData = new BitmapData(target_mc._width, target_mc._height, false, 0x00CCCCCC);
var mc_1:MovieClip = this.createEmptyMovieClip("reflect_mc", 2);
mc_1.attachBitmap(myBitmapData, 3);
myBitmapData.draw(target_mc);
reflect_mc._yscale = -100;
reflect_mc._y= target_mc._y+target_mc._height*2+20;
reflect_mc._x = target_mc._x;
}
And here is the complete code:
import flash.display.BitmapData;
this.createEmptyMovieClip("image_mc", 1);
var mclListener:Object = new Object();
mclListener.onLoadInit = function(target_mc:MovieClip) {
target_mc._x = (Stage.width/2)-(target_mc._width/2);
target_mc._y = 0;
reflect(target_mc);
};
var image_mcl:MovieClipLoader = new MovieClipLoader();
image_mcl.addListener(mclListener);
image_mcl.loadClip("none.jpg", image_mc);
function reflect(target_mc:MovieClip):Void{
var myBitmapData:BitmapData = new BitmapData(target_mc._width, target_mc._height, false, 0x00CCCCCC);
var mc_1:MovieClip = this.createEmptyMovieClip("reflect_mc", 2);
mc_1.attachBitmap(myBitmapData, 3);
myBitmapData.draw(target_mc);
reflect_mc._yscale = -100;
reflect_mc._y= target_mc._y+target_mc._height*2+20;
reflect_mc._x = target_mc._x; }
Hit “Ctrl+Enter” or go to “Control”, “Test Movie” to test our Flash movie. You should see this:
Now there’s a flipped copy of our picture below. Here is what the code does:
var myBitmapData:BitmapData = new BitmapData(target_mc._width, target_mc._height, false, 0x00CCCCCC);
We create a new instance of the BitmapData class and pass it the image_mc size as parameters which determines the size of the bitmap.
var mc_1:MovieClip = this.createEmptyMovieClip("reflect_mc", 2);
We create an empty movieClip.
mc_1.attachBitmap(myBitmapData, 3);
We attach the bitmap to the empty movieclip.
myBitmapData.draw(target_mc);
We draw the image_mc to the bitmap.
reflect_mc._yscale = -100;
reflect_mc._y= target_mc._y+target_mc._height*2+20;
reflect_mc._x = target_mc._x;
Then we flip the newly created movieclip and position it below the image_mc.
Still two steps to go, we are almost there.
Easing Explained for AS2 and AS3
by admin on May.25, 2009, under Tutorials
In this tutorial I will explain how easing works in relationship to the Tween class either in AS3 and AS2 and how you can easily modify existing easing classes to fit your needs or create your own easing methods. To understand this tutorial you should at least know how to use a tween in AS3 or AS2 and have also a basic understanding of classes.
So here is a basic tween (AS3):
var Xtween:Tween = new Tween(square,"x",Back.easeIn,square.x,square.x+100,1,true);
We create an instance of the Tween class: var Xtween:Tween = new Tween();
We pass a reference to an object: var Xtween:Tween = new Tween(square,
We tell which property of the object we want to tween: var Xtween:Tween = new Tween(square,"x",
We pass an easing function: var Xtween:Tween = new Tween(square,"x",Back.easeIn,
We pass a starting value: var Xtween:Tween = new Tween(square,"x",Back.easeIn,square.x,
We pass an ending value: var Xtween:Tween = new Tween(square,"x",Back.easeIn,square.x,square.x+100,
We pass a duration: var Xtween:Tween = new Tween(square,"x",Back.easeIn,square.x,square.x+100,1,
And finaly we tell if the duration will be expressed in seconds or in frames: var Xtween:Tween = new Tween(square,"x",Back.easeIn,square.x,square.x+100,1,true);
So already one word about the two last parameters, duration and type (seconds/frames), no matter what you choose, the tween will still use frames as a basis for its calculations. You can check that out easily by setting a frame rate to 1 and then run a Tween using seconds … not pretty right? So the frame rate matters even if you use seconds.
The Tween takes all the parameters and calculates how many frames it will need to go from the initial value (here square.x) to the final value (square.x+100), it then call the easing function this exact number of frames. So if the tween needs 30 frames to reach the final value, it will call the easing function 30 times. The Tween will call the easing
function with 4 parameters: First: The initial time (starting at zero of course) , second: The initial value of the property being tweened (in our example square.x) , third: The final value needed (100) , fourth: The total duration of the tween. The Tween expects to receive a number from the easing function each time it calls it. Fairly simple, let’s create our own easing function to see this in action:
var Ytween:Tween = new Tween(square,"y",crazyTween,square.y,square.y+100,1,true);
function crazyTween(TimeOrigin:Number,InitialValue:Number,FinalValue:Number,FinalTime:Number):Number{
if(TimeOrigin/FinalTime<1){
return FinalValue+Math.random()*200;
}else{return InitialValue+FinalValue;}
}
That’s right, we can pass our own easing function as long as we return a number! Try this awesome easing function and see, the tween uses it! If you trace all this you’ll see that the only value changng from call to call is the first one, the initial time. On a 30 frames tween, the initial time will go from 0 to 30, 30 being the duration time. Now you see why the useless crazyTween function was still able to end up at the right place. Now if we want to apply a linear motion, all we need is to divide the amount needed (in our example 100) by the number of frames needed and add that to the initial value:
var Ytween:Tween = new Tween(square,"y",normalTween,square.y,square.y+100,1,true);
var increase:Number = 100/30;
function normalTween(TimeOrigin:Number,InitialValue:Number,FinalValue:Number,FinalTime:Number):Number{
increase += 100/30;
return InitialValue+increase;
}
A perfect linear tween if you have a framerate of 30, now how do we translate so that no matter the number of frames needed it will always end up right?
Remember, the only value changing in the call to the easing function is the initial time. It’s gonna start with zero and end up being exactly the duration time so if we divide it by the duration time we get a ratio that we can use to calculate the amount we need to add to the initial value:
TimeOrigin/FinalTime this is our ratio. So FinalValue*(TimeOrigin/FinalTime) will give us the right amount we need to add each time but of course we need to add it to the initial value so the final formula is: InitialValue+FinalValue*(TimeOrigin/FinalTime) let’s try:
var Ytween:Tween = new Tween(square,"y",normalTween,square.y,square.y+100,1,true);
function normalTween(TimeOrigin:Number,InitialValue:Number,FinalValue:Number,FinalTime:Number):Number{
return InitialValue+FinalValue*(TimeOrigin/FinalTime)
}
Of course we always think about moving objects with tweens but look at this:
var theNumber:Number = 0;
var Ytween:Tween = new Tween(this,"theNumber",normalTween,0,300,1,true);
function normalTween(TimeOrigin:Number,InitialValue:Number,FinalValue:Number,FinalTime:Number):Number{
trace(InitialValue+FinalValue*(TimeOrigin/FinalTime))
return InitialValue+FinalValue*(TimeOrigin/FinalTime)
}
That’s right, we are tweening a simple variable!
Now before we move deeper into easing functions I want to point out the default easing method that can be found in the tween class. This default easing method is a linear easing exactly like the one we created and the tween class will run it if no easing function is provided so :
var Ytween:Tween = new Tween(this,"theNumber",null,0,300,1,true);
Will force the tween class to run its internal easing method. Note that this internal easing method is equivalent to the None easing class with AS2 and the Linear easing class with AS3.
GlobalTimer Class
by admin on May.14, 2009, under Tutorials
We use the GlobalTimer Class in all our projects. The GlobalTimer Class makes the creation of timers and the registration of functions/methods with the timer very easy. We’ll show you here some key features.
import GlobalTimer;
var my_timer:GlobalTimer = new GlobalTimer();
my_timer.register(my_function);
function my_function():void{
trace("hello");
}
As soon as you register a function with the GlobalTimer, the GlobalTimer starts (or not if you pass false as argument) with default values (10 milliseconds). You can of course pass other values at instantiation time or by accessing the timer regular properties (Timer class). Unregister the function and the timer stops:
my_timer.unregister(my_function);
You can register as many function as you want:
my_timer.register(my_function);
my_timer.register(my_function2);
This will cause the GlobalTimer to run the two functions. By default, passing the same function twice is prevented:
my_timer.register(my_function);
my_timer.register(my_function);//no results
Unregistering a function will not stop the timer if other functions are still registered. You can of course stop the timer anytime using normal Timer properties and methods (Timer class). There’s many other useful methods that you can discover on your own. Enjoy and leave us a comment.
Aswebcreations.com team.
Creating a Simple Slide Show with Actionscript 3.
by admin on May.03, 2009, under Tutorials
In this tutorial you will learn how to create a professional slide show using AS3 with Flash CS3. I will also show you a simple design pattern that will help you organize your code efficiently.
What exactly is a professional slide show as opposed to a non-professional one?
A professional slide show loads pictures externally and then displays them and applies to them any effect available. This makes the integration of the slide show into a CMS very easy.
Pretty simple but how does it do this?
The slide show loads externally the paths of the pictures to display. This can be done by loading into the Flash application an XML file, a text file, or even directly a server side script. Then the slide show uses the paths to load the pictures and apply to them the required effect.
So we can break up our slide show into three major functionalities:
- Loading the external data (picture paths).
- Loading the pictures using the data.
- Applying the effect.
So let’s get started. First download this folder here, open the Fla file called “loading_data_1.fla” with Flash CS3 and then let me walk you through the code …
Step 1, Loading the External Data:
Our slide show will load external pictures but to do this the application needs to know where to find the pictures so the first thing to do is to provide this information to the application. We will do this with an XML file and the reason we use XML is that Flash strongly supports it. Also, XML is quite a standard now on the web for transmitting data across Internet. The XML I used for this tutorial is called “setup.xml” and is included in the folder you downloaded. Feel free to take a look at it and see how everything is structured. Now let’s dig in the code:
First, we create a “URLRequest”. This will hold the path to the XML:
Now we create a “URLLoader”. This will be used to load an external text/XML file in AS3.
Loading external data with Flash is asynchronous, which means we can use the data only when it’s completely loaded, not before that. Bottom line: we can’t start our slide show before being sure the XML file has been loaded.
All we need is register an event that will tell us when the data is ready:
We registered an event with the “loader” variable which will trigger the “completeHandler” function only when the XML is fully loaded.
Now we create the completeHandler function:
trace(loader.data)
}
The function will simply trace the data loaded into the Flash output panel.
Finaly I can load my XML:
Why do I load the XML at the very end? It seems logical to load first and then write all the other code to handle the incoming data. Remember Flash is asynchronous and because of that if we load first and then write the rest of the code, the data (especially when cached by the browser) could sometimes be loaded before Flash has the time to read the rest of the code. What would happen in this case? The event that is supposed to tell us when the data is loaded will never run, and so the application as a whole will stop.
Here is the full code so far:
var loader:URLLoader = new URLLoader();
loader.addEventListener(Event.COMPLETE, completeHandler);
function completeHandler(e:Event):void{
trace(loader.data)
}
loader.load(request_xml);
Go ahead and run this example you should see the XML showing in the output panel. If you don’t, check that your paths are correct.
Our variable “loader” holds now the data we need but unfortunately this variable doesn’t know it’s an XML so we can’t start to use the data yet. We need to convert the data to a valid XML object, let’s see that now by opening the file “loading_data_2.fla”.
Our slide show now has our XML data but the weird thing is: It doesn’t know it’s XML data! It could be a text, XML, variables or whatever so our next step is to cast our data to an XML object so then our application will know what to do with it:
We create an XML object:
Then in our “completeHandler” function we convert our data to an XML like this:
And the full code:
var request_xml:URLRequest = new URLRequest(”setup.xml”);
var loader:URLLoader = new URLLoader();
loader.addEventListener(Event.COMPLETE, completeHandler);
function completeHandler(e:Event):void{
xml_data = new XML(loader.data);
}
loader.load(request_xml);
It’s done, our XML data is now available, let’s now store it in an array.
Note that it’s purely optional, we could also just use the built in XML classes directly instead of using an array.
We create an array:
Then we set up a for loop inside the “completeHandler” function to store the picture paths in our array:
array_of_picture.push(xml_data.child(i));
}
The “xml_data.children().length()” will tell us how many pictures we have so the for loop will run as many times as needed. We store the paths in the array using “xml_data.child(i)” which will run through each node in the XML and add the path in the array.
Complete code:
var array_of_picture:Array = new Array();
var request_xml:URLRequest = new URLRequest(”setup.xml”);
var loader:URLLoader = new URLLoader();
loader.addEventListener(Event.COMPLETE, completeHandler);
function completeHandler(e:Event):void{
xml_data = new XML(loader.data);
for(var i:int; i<xml_data.children().length(); i++){
array_of_picture.push(xml_data.child(i));
}
}
loader.load(request_xml);
Now our application knows where to find our pictures so it’s time to create our slide show engine. We can go ahead and add a call to a start_slide_show function and then define the body of the function:
var array_of_picture:Array = new Array();
var request_xml:URLRequest = new URLRequest(”setup.xml”);
var loader:URLLoader = new URLLoader();
loader.addEventListener(Event.COMPLETE, completeHandler);
function completeHandler(e:Event):void{
xml_data = new XML(loader.data);
for(var i:int; i<xml_data.children().length(); i++){
array_of_picture.push(xml_data.child(i));
}
start_slide_show();//let’s start the slide show!
}
loader.load(request_xml);
function start_slide_show(){
trace(”ready to roll!”)
}
Of course our start_slide_show() function doesn’t do much so far but we’ll fix that on Step 2:
Working with XML in Actionscript 2
by admin on May.02, 2009, under Tutorials
Working with XML in Actionscript 2.
When it comes to loading data in a Flash application, most Flash developer think about XML. The reason is, Actionscript has many built in classes for XML manipulation that are efficient and easy to use. It’s not rare to see a Flash developer make their server script create an xml and then have Flash read and parse the XML while they could have just loaded the data directly from the server script into Flash. Again, the reason is: it’s easier to do it like that! In this tutorial, I’ll show you how to load a XML and then use the data loaded from it.
1. First let’s create a basic xml document, open your favorite XML editor (like the fancy Notepad) and write that:
<example>
<Flash>myFlash.swf</Flash>
<image>myGraphic.jpg</image>
<text>I can write a text too, why not?</text>
</example>
I save this as “example.xml”, then I create a little swf named “myFlash.swf”, and a little jpg named “myGraphic.jpg”.
2. Open your Flash software, select “new”, “Flash document”, click “Ok”, then go to “Modify”, “Document”, enter 300 for the width and heigth and enter 30 for the frame rate, save the document as “xml.fla” (Note: for this example all document and file must be in the same folder).
3. Go to “window”, “Components”, then click on “User Interface” to open it, then drag 3 button component onto the stage. You should have this:
.
4. Now go to “window”, “Component Inspector” to open it.
5. Click on each button on the stage, you will see their properties displayed in the component inspector.
6. With one button selected, on the component inspector, there’s a line named “label” with a value of “button”, change the value to “SWF”, for the first button, then “JPG” for the second button, then “TEXT” for the last one, now you should have this:
7. Now for each of these buttons we need to give an instance name.
8. Select the “SWF” button and give it an instance name of “swf_btn” , repeat this for the “JPG” button, give a name of “jpg_btn” , and for the “TEXT” button, “text_btn”.
9. Now copy and paste this code in the Actions panel:
loadText();
}
text_btn.addEventListener(”click”, Textclicked);
function swfclicked(){
loadSwf();
}
swf_btn.addEventListener(”click”, swfclicked);
function jpgclicked(){
loadJpg();
}
jpg_btn.addEventListener(”click”, jpgclicked);
We define an event listener for our 3 buttons, when they are clicked, they call a function that we will write later.
10. We create an array that will hold the XML.
We will use it to store all the information coming from the XML. Now let’s load the XML:
XMLtoLoad.ignoreWhite = true;
XMLtoLoad.onLoad = function(success) {
theXML=XMLtoLoad.childNodes[0].childNodes;
};
XMLtoLoad.load(”example.xml”);
We create an XML object (XMLtoLoad), we get rid of any white space the XML might have, we define a function that will trigger when the XML is fully loaded (onLoad), in this function we assign the XML data to the array we created earlier, finally we load the XML.
11. Now we have our data so let’s parse it, we are going to create the functions that the buttons call:
var theText:String = theXML[2].firstChild.toString();
this.createTextField(”my_txt”, 10, 75, 200, 300, 22);
my_txt.text = theText;
}
function loadJpg(){
this.createEmptyMovieClip(”my_jpg”, 10);
my_jpg._x=50;
my_jpg._y=150;
my_jpg.loadMovie(theXML[1].firstChild);
}
function loadSwf(){
this.createEmptyMovieClip(”my_swf”, 10);
my_swf._x=50;
my_swf._y=150;
my_swf.loadMovie(theXML[0].firstChild);
}
Our application is now finished! the loadText function first creates a string variable and assign to it the third element in the theXML array, it also converts it to a string. Then it creates an empty textfield, position it and assign in it the text from the XML. The loadJpg function creates an empty movie clip, position it and load into it the jpg defined in the XML. The loadSwf function does the same.
Click on each buttons to display the swf, jpg, or text.
TIP: When you click on a button, what was displayed before disappears but I did not write any code for that so why is it doing that?
When you create a textfield or an empty movieclip, you need to assign a depth value (I gave a depth of 10 to all of them), but in Flash only one object can occupy a certain depth, so if you assign the same depth to another object, the object that was at the same depth before is removed automaticaly!
Drawing shapes with AS2
by admin on May.01, 2009, under Tutorials
Drawing shapes with AS2
Drawing any shapes with Actionscript2 is very easy. In this tutorial I will show you how to draw a basic shape and then how to apply this knowledge into a dynamic application.
1. Open your Flash software, select "new", "Flash document", click "Ok", then go to "Modify", "Document", enter 300 for the width and heigth and enter 30 for the frame rate.
2. Open the "Actions" panel.
3. Copy and Paste this code:
square_mc.lineStyle(5, 0xff00ff, 100, true, "none", "round", "miter", 1);
square_mc.beginFill(0xFF0000);
square_mc.moveTo(10, 10);
square_mc.lineTo(100, 10);
square_mc.lineTo(100, 100);
square_mc.lineTo(10, 100);
square_mc.lineTo(10, 10);
square_mc.endFill();
4. Hit "Ctrl+Enter" or go to "Control", "Test Movie" to test our Flash movie. You should see this:
Here is what the code does:
The "this" keyword similar to the one in Javascript refers to the actual "root" of the Flash movie, createEmptyMovieClip is a method of the movieclip class with which we can create dynamic movieclip at run time, it takes two arguments: 1. the name we give it. 2. the depth (z-index). So far, this movieclip is empty, meaning it has no shape, size, color and so on, so let’s fix that and draw something inside it.
Now that we created "square_mc" we can reference it in the code. Here we apply the lineStyle method. It will add a line around the shape we will draw later on. It takes 8 arguments:
1. thickness. 2. color. 3. alpha(transparency) . 4. pixelHinting . 5. the way to react to scaling (default : none) . 6. style of the line. 7 style of the "joint" line. 8. a value that affects how the style "miter" behaves.
beginFill is a method that applies a fill color, it takes 1 argument and must be ended by a endFill method (see later).
We are about to draw but before that we need to tell Flash where to start. With the method moveTo we are here telling Flash to go to 10 pixel right and 10 pixel down starting from the left top corner of the Flash movie itself.
Now we draw with the lineTo method. here we tell flash to draw from the point defined with moveTo to 100 pixels to the right of the left top corner and 10 pixels down from the left top corner.
square_mc.lineTo(10, 100);
square_mc.lineTo(10, 10);
lineTo(100, 100) : bottom right corner of the square. lineTo(10, 100) : bottom left corner of the sqaure. lineTo(10, 10) : top left corner of the sqaure.
Time to put some color! We tell Flash we are done drawing and it can now apply the fill.
Fairly easy isn’t it? If we use only 3 lineTo we will draw a triangle. You can add as many lineTo as you want and draw any shapes. There is also a curveTo method to draw circles and ovals. Now let’s do a simple dynamic application of what we learned here.
Drawing curves with AS2
by admin on May.01, 2009, under Tutorials
Logical following of the "Drawing shapes" tutorial, here comes the "Drawing curves" tutorial. Most likely, it will be followed by a "Drawing lines" tutorail. So let’s get started and draw some curves!
1. Open your Flash software, select "new", "Flash document", click "Ok", then go to "Modify", "Document", enter 300 for the width and heigth and enter 30 for the frame rate.
2. Open the "Actions" panel.
3. Copy and Paste this code:
with (circle_mc) {
beginFill(0xFF0000);
moveTo(100, 100);
curveTo(200,0,300,100);
curveTo(400,200,300,300);
curveTo(200,400,100,300);
curveTo(0,200,100,100);
endFill();
}
4. Hit "Ctrl+Enter" or go to "Control", "Test Movie" to test our Flash movie. You should see this:
I know it’s not pretty, it doesn’t look like a circle but actually to draw a nice circle we really need to know how the curveTo() method works so let’s go on:
We know this line already, we used pratically exactly the same for the preceding tutorial, we create a new movie clip and give it a depth (1).
That’s a new line, in fact we use the keyword "with" and assign to it the new movie clip name we just created. Now everything between the next two brackets will refer to "circle_mc" which will save us some typing.
beginFill is a method that applies a fill color, we used it in the preceding tutorial.
We need to start drawing somewhere so we use the moveTo() method to go to 100 on the x coordinate and 100 on the y coordinate.
Here is where we start drawing a curve but unlike the lineTo() method here we need to give 4 numbers to the method to be able to draw a curve. So what are these numbers and what do they do? Well, the first and second number give a x and y coordinate for a point called control point and I’ll come back to that in a few second. The third and fourth numbers give a x and y coordinate which is the end of the actual curve, let’s see that in these following examples:
Flash uses the control point to draw the actual curve:
So now we can figure out what the numbers do in this code:
curveTo(200,0,300,100);
curveTo(400,200,300,300);
curveTo(200,400,100,300);
curveTo(0,200,100,100);
the red numbers above tell Flash where to start and stop drawing:
curveTo(<200,0,300,100);
curveTo(400,200,300,300);
curveTo(200,400,100>,300);
curveTo(0,200,100,100);
Now the numbers in blue tell flash where the control points to use to draw the curve are:
Still, why can’t we draw a circle that look like a circle? Well, we used only 4 curveTo() and that’s not enough to draw a nice shaped circle so we need more curveTo() to acheive a nice result. Let’s do that in the second part…