AS2 OOP: Inheritance
by senocular
Extends
The keyword that makes inheritance possible with ActionScript 2.0 is extends. This keyword allows for a class to inherit properties and methods from another. It's used once in the class definition directly after the name of the class being defined. Following the extends keyword is the class name of the class you intend to inherit from - the intended super class.
class thisClassName extends superClassName { ...
The following example is a new class that extends or inherits from the class Person.
class Geek extends Person {
static var OSofChoice:String = "Linux";
var iq:Number;
function Geek (n:Number) {
iq = n;
}
function doYouKnow (language:String):Boolean {
switch (language) {
case "C++": return true;
case "Java": return true;
case "PHP": return true;
case "Laymen's": return false;
default: return true;
}
}
}
Geeks are people too, right? With Geek extending Person, it now has gained all properties and has access to all methods within the Person class. Here is the ActionScript 1.0 equivalent.
/* ActionScript 1.0 */
Geek = function(n) {
iq = n;
};
Geek.OSofChoice = "Linux";
Geek.prototype = new Person(); // inherit from Person
Geek.prototype.doYouKnow = function(language) {
switch (language) {
case "C++": return true;
case "Java": return true;
case "PHP": return true;
case "Laymen's": return false;
default: return true;
}
};
Notice the term "prototype" in the ActionScript 2.0 version is nowhere to be found. Its simply a matter of class extends super class and you're done.
Now, when I said using extends allowed access to all the methods of the super class, I meant all the methods; normal class methods, private methods and even static methods. That's right, static methods too, something you didn't so easily get with ActionScript 1.0. In ActionScript 2.0, they're readily accessible and easy to access. Lets start another example that better demonstrates this. Two classes with simple descriptive names to help keep track of what's going on (nothing gimmicky or too amusing like the Geek class I'm sure so many of you could relate so well to ;)
// in SuperClass.as
class SuperClass {
static var ssp:String = "super static property";
public var spubp:String = "super public property";
private var sprip:String = "super private property";
static function ssm():Void {
trace("super static method");
}
public function spubm():Void {
trace("super public method");
}
private function sprim():Void {
trace("super private method");
}
}
// in SubClass.as
class SubClass extends SuperClass {
function SubClass() {
trace(ssp);
trace(spubp);
trace(sprip);
ssm();
spubm();
sprim();
}
}
// in Flash movie
var instance:SubClass = new SubClass();
/* output:
super static property
super public property
super private property
super static method
super public method
super private method
*/
Anything usable in the super class is also usable in the sub class thanks to extends. It takes care of everything for you. Just be careful to note that this is the class itself and not necessarily the instances of that class. Instances, for example, can't directly access an inherited static property. Only other methods within the subclass (which themselves can be called from an instance) can do that. Instances are restricted to non-static methods.
With that in mind, let's take another look at Math2. Remember Math2 was an object that provided a space to add Math related functions, such as randRange, since now, by default, the Math object no longer allows custom functions to be added to it (it's not a dynamic class). Because extends allows inheritance of all class methods, even static ones, we might consider making Math2 extend Math, right?
class Math2 extends Math {
// ... custom Math functions ...
}
But what does this do? Doesn't it give access of Math related static methods to Math2? Well it does, at least to Math2 methods. It does not, however, give the methods to the Math2 class object itself. It's that Math2 object which is used in calling those methods in the first place. Well, what about an instance of Math2 then? Nope. Same issue there. An instance of Math2 is no more capable of calling inherited static methods as Math2 itself is. You'll just have to use your own custom math methods in Math2 and use Math when you need native Flash math methods. This doesn't mean you can't still extend the Math class, though. At least Math methods won't have to be referenced using the Math object.
class Math2 extends Math {
static function randRange(low:Number, high:Number):Number {
// readily accessible Math methods like floor
// random is an exception because of the
// existence of the top level function random()
return low + floor(Math.random()*(high-low+1));
}
}
The extends keyword can also be used with interfaces. Interfaces using extends can only extend other interfaces and not other classes. This lets you include definitions from one interface into another very easily.
// in SimpleBlockingStyle.as
interface SimpleBlockingStyle {
function block():Void;
}
// in SimpleFightingStyle.as
interface SimpleFightingStyle extends SimpleBlockingStyle {
function headButt():Boolean;
function kick(foot:String):Boolean;
}
You can also use extends with classes implementing interfaces, but you'll need to be sure to use the extends keyword before implements. This is a requirement of the compiler.
class className extends superClass implements interface { ...
When you inherit from a super class this way, those super class methods, now accessible to the current (sub) class, will be accounted for in the interface interface. So if you think about it, the compiler, when reading this line of code, will need to know all the methods that class has access to (its own and those inherited) so it can properly check to see if those outlined in the interface are present. This might help you remember the order.
class FookYoo extends MartialArt implements SimpleFightingStyle {
// ...
}
Despite the apparent ease of access to the super class, sometimes you may still need to be more specific in you're referencing of that class. That can be accomplished using super.
Super
In ActionScript 1.0, the super command was used to gain access the super class directly, most commonly to call the super class constructor to initialize the subclass, though it gave access to both the constructor as well as methods. Good news! Super is still here with ActionScript 2.0. Better news! If you don't include the super() call in your subclass's constructor function (much in the way of the constructor itself). Flash will add it for you!
One new restriction included with super's use in ActionScript 2.0 is that when using it to call the super class constructor in a sub class, you'll need to be sure you call it as the very first thing in the subclass's constructor. Otherwise, the compiler will complain and give you an error. This isn't necessarily a bad thing though. This is where super is supposed to be called. So it's good the compiler lets you know when you've faltered in doing otherwise. This is also where its called if you don't include it yourself. Calling it yourself, though, allows you to pass arguments into the super class call. When its called automatically, its run without any arguments passed.
Example.
// in Furniture.as
class Furniture {
var material:String;
function Furniture(madeOf:String) {
material = madeOf;
}
function describe():Void {
trace("Made of fine quality "+ material +".");
}
}
// in Chair.as
class Chair extends Furniture {
var legs:Number;
function Chair(madeOf:String, legCount:Number) {
super(madeOf);
legs = legCount;
}
function describe():Void {
trace("Complete with "+ legs +" legs.");
super.describe();
}
}
// in Flash movie
var item:Chair = new Chair("Mahogany", 4);
item.describe();
/* output:
Complete with 4 legs.
Made of fine quality Mahogany.
*/
Try it yourself! (zipped source)
Chair is a sub class of Furniture. Super is used to pass arguments to the Furniture constructor when called and to access a similarly named method within one of its own - just like in ActionScript 1.0.
Monday, May 10, 2010
Sunday, May 9, 2010
Classes in ActionScript 2
Actionscript 2.0 Basics
In order to learn Actionscript 2.0, you must first learn some vocabulary. We will examine each of these in further detail. This is just a short list that we will add to as our discussion continues.
Class — encapsulates data (variables, attributes, etc.) and methods (functions, methods, etc).
Instance — the actual implementation of a class.
Method — a function inside of a class that performs a specific operation.
Classes in Actionscript 2.0
When learning, I like to have solid examples of code to work from. So here is your first code from the Product.as file:
class Product {
}
There are some important things to understand about this code:
The name of the file Product.as is the same as the name of the class Product.
You will want to put this code into a package to make it more user-friendly and easier to distribute.
Packages in Actionscript 2.0
A package is nothing more than a folder that contains one or more Actionscript 2.0 classes. Most packages are placed in multiple folders from generic to specific. For example, my package is com.ahfx.Product. I have a folder named com. In that folder I have another folder called ahfx. In that folder I have a class file, Product.as. When I distribute my Actionscript 2.0 classes, I will merely send the folder com to the organization that needs to use my classes. (If you notice you just invert your domain name ahfx.com to get your package name, com.ahfx. Packages also help distinquish between classes with the same name. For example if you wrote a class called Product, we could use the package to tell which Product we really wanted to use). To reflect the package change I will add that to my Actionscript 2.0 class code, Product.as.
class com.ahfx.Product {
}
Build It
We are now going to help you set up your very first Actionscript 2.0 class. We will first create the package, then start Flash MX 2004 and write our first actionscript.
Browse on your computer to your Flash MX 2004 installation folder (for example: C:\Program Files\Macromedia\Flash MX 2004\en
Go to the <—Macromedia install folder—>First Run\Classes\ folder
In this folder (Classes) create a new folder named com
Open the com folder you just created and create a new folder named ahfx
I would now add a shortcut to this ahfx folder on you desktop.(Just for ease of access).
Open Flash MX 2004
Choose "Create New: Actionscript File"
Copy the code from Product.as above into the new window
Choose File|Save As and save it in the ahfx folder you created above.(If you added a shortcut to your desktop, click desktop, click the shortcut and it will take you to the correct folder).
After saving, press Ctrl-t to check your syntax (Hopefully everything will be fine). If you get errors, make sure your file is named the same as the class name, and that you placed the file in the correct folder.
Actionscript 2.0 Constructor
This actionscript class won't do much as of yet. We can't even create an instance of our class yet. We must create a constructor. A constructor is a special method that creates an instance of an Actionscript 2.0 class. A constructor has the same name as the class. The code now reads like this for Product.as.
class com.ahfx.Product {
function Product() {
}
}
Now that we have created a constructor. We could create an actual Product in a Flash application from our Actionscript 2.0 class Product.as (We will examine the Flash side in a while).
Actionscript 2.0 Attributes
However, even though we could create an instance, this also wouldn't do much. Lets add some data (the first half of an Actionscript 2.0 class) to our actionscript class. This class will describe Products that will go in a Shopping Cart (Creating the shopping cart is found in the Intermediate lesson). Our basic product with have a description, a price, and a quantity. Although this is a very simple example, you could add more attrinbutes later.
class com.ahfx.Product {
//Instance Variables
private var price:Number;
private var desc:String;
private var quantity:Number;
function Product() {
}
}
private — Tells the class that only this actionscript class and its subclasses can access this variable.
var — Tells the Actionscript 2.0 class that this is a variable.
:Datatype — Anything after the : is the datatype of the variable. (For example Number above).
These variables are instance variables. This means that every time we create an instance of a Product, it will have its own desc, price, and quantity.For example, we could create a Product with a desc="Teddy Bear", price=14.99, and quantity=3. We could then create another Product with a desc="Soyo Motherboard", price=68.99, and quantity=1. Each of these Products is an instance. They have their own variables.
Get and Set Actionscript 2.0 Variables
Now that we have the first part of an actionscript class done(the data part), we will begin on the second part(the methods). Because we have declared the variables to be private, we must create get and set methods for the variables. This allows our Flash application to read and write to the variables.
class com.ahfx.Product {
//Instance Variables
private var price:Number;
private var desc:String;
private var quantity:Number;
function Product() {
}
function getPrice():Number {
return price;
}
function setPrice(price:Number):Void {
this.price = price;
}
}
Lets examine the getPrice() function first. getPrice() is the name of the function. :Number is the return type. This means that you could write the following code in your Flash application, var myPrice:Number = myProduct.getPrice();, because getPrice() returns a Number. return price; takes the instance variable "price" and returns it to the program that called it.
Next lets examine the setPrice() function in our Actionscript 2.0 class. setPrice() is the name of the function. This function passes (or sends) one variable which is a Number. We will use the name "price" for this local variable. This class doesn't return anything and so the return type is :Void. this.price is a reference to the instance variable price while = price is a reference to the local variable price.
We could have written the code like this also.
class com.ahfx.Product {
//Instance Variables
private var price:Number;
private var desc:String;
private var quantity:Number;
function Product() {
}
function getPrice():Number {
return price;
}
function setPrice(myVar:Number):Void {
price = myVar;
}
}
The local variable is myVar this time instead of price. Because we don't have a local variable with the same name as an instance variable we don't need to clarify which price we were talking about and we don't need to add this. in front of price.
Actionscript 2.0 Methods
I´ve added the other getters and setters. (You use getters and setters to control the values that may be placed into that variable. For example, you couldn't have a negative cost of a product. So you could create some code that checks to see if the value passed to the set method it negative. If it was negative, don't assign the number. You could also check for not number values being passed.
class com.ahfx.Product {
//Instance Variables
private var price:Number;
private var desc:String;
private var quantity:Number;
function Product() {
}
function getPrice():Number {
return price;
}
function setPrice(myVar:Number):Void {
price = myVar;
}
function getQuantity():Number {
return quantity;
}
function setQuantity(quantity:Number):Void {
this.quantity = quantity;
}
function getDesc():String {
return desc;
}
function setDesc(myVar:String):Void {
desc = myVar;
}
}
Now we will add one other method, getTotal. This method will return a number that will tell us the total cost of this product (price times quantity)
class com.ahfx.Product {
//Instance Variables
private var price:Number;
private var desc:String;
private var quantity:Number;
function Product() {
}
function getPrice():Number {
return price;
}
function setPrice(myVar:Number):Void {
price = myVar;
}
function getQuantity():Number {
return quantity;
}
function setQuantity(quantity:Number):Void {
this.quantity = quantity;
}
function getDesc():String {
return desc;
}
function setDesc(myVar:String):Void {
desc = myVar;
}
function getTotal():Number {
return price*quantity;
}
}
This method takes no parameters and returns a Number. You see that it will return price*quantity. Next we will examine the Flash to use this class.
Actionscript 2.0 Flash Implementation
Now we are going to take our new Actionscript 2.0 class and use it in a Flash application. Make sure that you have saved the final version of your actionscript and close down Flash. Open it back up and this time start a new Flash Document. Create a keyframe and enter the following code:
import com.ahfx.Product;
var myProduct = new Product();
myProduct.setQuantity(3);
myProduct.setPrice(2.99);
myProduct.setDesc("Teddy Bear");
trace(myProduct.getDesc());
trace(myProduct.getPrice());
trace(myProduct.getQuantity());
trace(myProduct.getTotal());
This will output the following:
Teddy Bear
2.99
3
8.97
The first line tells the compiler to import the Product class we had just created. The next line creates an instance of the Product class. Now we start assigning values into the product. This product is a Teddy Bear that costs 2.99, and the person wants 3 of them. The trace statements just print out the values of this product. That was easy wasn´t it. Let´s make another product.
import com.ahfx.Product;
var myProduct = new Product();
myProduct.setQuantity(3);
myProduct.setPrice(2.99);
myProduct.setDesc("Teddy Bear");
trace(myProduct.getDesc());
trace(myProduct.getPrice());
trace(myProduct.getQuantity());
trace(myProduct.getTotal());
var myOtherProduct = new Product();
myOtherProduct.setQuantity(1);
myOtherProduct.setPrice(12.99);
myOtherProduct.setDesc("Cool Sunglasses");
trace(myOtherProduct.getDesc());
trace(myOtherProduct.getTotal());
myOtherProduct.setQuantity(2);
trace(myOtherProduct.getTotal());
Notice that we don´t need another import statement. All we do is create another instance of our Actionscript 2.0 class. This instance is named myOtherProduct. It is a pair of cool sunglasses that cost 12.99. The customer decides to get an extra pair (because they are so cool) so we call the setQuantity method and pass it the parameter of 2. You can see that the total automatically updates itself in the new output:
Teddy Bear
2.99
3
8.97
Cool Sunglasses
12.99
25.98
This ends the basic Actionscript 2.0 lesson. Although this has been a simple walkthrough, this is a solid base that we wish to build upon. If you continue to the intermediate page, you will learn how to take the product you have created and place it in a shopping cart class.
Continue to intermediate page.
We would love to hear your feedback. Please email us as info AT ahfx DOT com.
In order to learn Actionscript 2.0, you must first learn some vocabulary. We will examine each of these in further detail. This is just a short list that we will add to as our discussion continues.
Class — encapsulates data (variables, attributes, etc.) and methods (functions, methods, etc).
Instance — the actual implementation of a class.
Method — a function inside of a class that performs a specific operation.
Classes in Actionscript 2.0
When learning, I like to have solid examples of code to work from. So here is your first code from the Product.as file:
class Product {
}
There are some important things to understand about this code:
The name of the file Product.as is the same as the name of the class Product.
You will want to put this code into a package to make it more user-friendly and easier to distribute.
Packages in Actionscript 2.0
A package is nothing more than a folder that contains one or more Actionscript 2.0 classes. Most packages are placed in multiple folders from generic to specific. For example, my package is com.ahfx.Product. I have a folder named com. In that folder I have another folder called ahfx. In that folder I have a class file, Product.as. When I distribute my Actionscript 2.0 classes, I will merely send the folder com to the organization that needs to use my classes. (If you notice you just invert your domain name ahfx.com to get your package name, com.ahfx. Packages also help distinquish between classes with the same name. For example if you wrote a class called Product, we could use the package to tell which Product we really wanted to use). To reflect the package change I will add that to my Actionscript 2.0 class code, Product.as.
class com.ahfx.Product {
}
Build It
We are now going to help you set up your very first Actionscript 2.0 class. We will first create the package, then start Flash MX 2004 and write our first actionscript.
Browse on your computer to your Flash MX 2004 installation folder (for example: C:\Program Files\Macromedia\Flash MX 2004\en
Go to the <—Macromedia install folder—>First Run\Classes\ folder
In this folder (Classes) create a new folder named com
Open the com folder you just created and create a new folder named ahfx
I would now add a shortcut to this ahfx folder on you desktop.(Just for ease of access).
Open Flash MX 2004
Choose "Create New: Actionscript File"
Copy the code from Product.as above into the new window
Choose File|Save As and save it in the ahfx folder you created above.(If you added a shortcut to your desktop, click desktop, click the shortcut and it will take you to the correct folder).
After saving, press Ctrl-t to check your syntax (Hopefully everything will be fine). If you get errors, make sure your file is named the same as the class name, and that you placed the file in the correct folder.
Actionscript 2.0 Constructor
This actionscript class won't do much as of yet. We can't even create an instance of our class yet. We must create a constructor. A constructor is a special method that creates an instance of an Actionscript 2.0 class. A constructor has the same name as the class. The code now reads like this for Product.as.
class com.ahfx.Product {
function Product() {
}
}
Now that we have created a constructor. We could create an actual Product in a Flash application from our Actionscript 2.0 class Product.as (We will examine the Flash side in a while).
Actionscript 2.0 Attributes
However, even though we could create an instance, this also wouldn't do much. Lets add some data (the first half of an Actionscript 2.0 class) to our actionscript class. This class will describe Products that will go in a Shopping Cart (Creating the shopping cart is found in the Intermediate lesson). Our basic product with have a description, a price, and a quantity. Although this is a very simple example, you could add more attrinbutes later.
class com.ahfx.Product {
//Instance Variables
private var price:Number;
private var desc:String;
private var quantity:Number;
function Product() {
}
}
private — Tells the class that only this actionscript class and its subclasses can access this variable.
var — Tells the Actionscript 2.0 class that this is a variable.
:Datatype — Anything after the : is the datatype of the variable. (For example Number above).
These variables are instance variables. This means that every time we create an instance of a Product, it will have its own desc, price, and quantity.For example, we could create a Product with a desc="Teddy Bear", price=14.99, and quantity=3. We could then create another Product with a desc="Soyo Motherboard", price=68.99, and quantity=1. Each of these Products is an instance. They have their own variables.
Get and Set Actionscript 2.0 Variables
Now that we have the first part of an actionscript class done(the data part), we will begin on the second part(the methods). Because we have declared the variables to be private, we must create get and set methods for the variables. This allows our Flash application to read and write to the variables.
class com.ahfx.Product {
//Instance Variables
private var price:Number;
private var desc:String;
private var quantity:Number;
function Product() {
}
function getPrice():Number {
return price;
}
function setPrice(price:Number):Void {
this.price = price;
}
}
Lets examine the getPrice() function first. getPrice() is the name of the function. :Number is the return type. This means that you could write the following code in your Flash application, var myPrice:Number = myProduct.getPrice();, because getPrice() returns a Number. return price; takes the instance variable "price" and returns it to the program that called it.
Next lets examine the setPrice() function in our Actionscript 2.0 class. setPrice() is the name of the function. This function passes (or sends) one variable which is a Number. We will use the name "price" for this local variable. This class doesn't return anything and so the return type is :Void. this.price is a reference to the instance variable price while = price is a reference to the local variable price.
We could have written the code like this also.
class com.ahfx.Product {
//Instance Variables
private var price:Number;
private var desc:String;
private var quantity:Number;
function Product() {
}
function getPrice():Number {
return price;
}
function setPrice(myVar:Number):Void {
price = myVar;
}
}
The local variable is myVar this time instead of price. Because we don't have a local variable with the same name as an instance variable we don't need to clarify which price we were talking about and we don't need to add this. in front of price.
Actionscript 2.0 Methods
I´ve added the other getters and setters. (You use getters and setters to control the values that may be placed into that variable. For example, you couldn't have a negative cost of a product. So you could create some code that checks to see if the value passed to the set method it negative. If it was negative, don't assign the number. You could also check for not number values being passed.
class com.ahfx.Product {
//Instance Variables
private var price:Number;
private var desc:String;
private var quantity:Number;
function Product() {
}
function getPrice():Number {
return price;
}
function setPrice(myVar:Number):Void {
price = myVar;
}
function getQuantity():Number {
return quantity;
}
function setQuantity(quantity:Number):Void {
this.quantity = quantity;
}
function getDesc():String {
return desc;
}
function setDesc(myVar:String):Void {
desc = myVar;
}
}
Now we will add one other method, getTotal. This method will return a number that will tell us the total cost of this product (price times quantity)
class com.ahfx.Product {
//Instance Variables
private var price:Number;
private var desc:String;
private var quantity:Number;
function Product() {
}
function getPrice():Number {
return price;
}
function setPrice(myVar:Number):Void {
price = myVar;
}
function getQuantity():Number {
return quantity;
}
function setQuantity(quantity:Number):Void {
this.quantity = quantity;
}
function getDesc():String {
return desc;
}
function setDesc(myVar:String):Void {
desc = myVar;
}
function getTotal():Number {
return price*quantity;
}
}
This method takes no parameters and returns a Number. You see that it will return price*quantity. Next we will examine the Flash to use this class.
Actionscript 2.0 Flash Implementation
Now we are going to take our new Actionscript 2.0 class and use it in a Flash application. Make sure that you have saved the final version of your actionscript and close down Flash. Open it back up and this time start a new Flash Document. Create a keyframe and enter the following code:
import com.ahfx.Product;
var myProduct = new Product();
myProduct.setQuantity(3);
myProduct.setPrice(2.99);
myProduct.setDesc("Teddy Bear");
trace(myProduct.getDesc());
trace(myProduct.getPrice());
trace(myProduct.getQuantity());
trace(myProduct.getTotal());
This will output the following:
Teddy Bear
2.99
3
8.97
The first line tells the compiler to import the Product class we had just created. The next line creates an instance of the Product class. Now we start assigning values into the product. This product is a Teddy Bear that costs 2.99, and the person wants 3 of them. The trace statements just print out the values of this product. That was easy wasn´t it. Let´s make another product.
import com.ahfx.Product;
var myProduct = new Product();
myProduct.setQuantity(3);
myProduct.setPrice(2.99);
myProduct.setDesc("Teddy Bear");
trace(myProduct.getDesc());
trace(myProduct.getPrice());
trace(myProduct.getQuantity());
trace(myProduct.getTotal());
var myOtherProduct = new Product();
myOtherProduct.setQuantity(1);
myOtherProduct.setPrice(12.99);
myOtherProduct.setDesc("Cool Sunglasses");
trace(myOtherProduct.getDesc());
trace(myOtherProduct.getTotal());
myOtherProduct.setQuantity(2);
trace(myOtherProduct.getTotal());
Notice that we don´t need another import statement. All we do is create another instance of our Actionscript 2.0 class. This instance is named myOtherProduct. It is a pair of cool sunglasses that cost 12.99. The customer decides to get an extra pair (because they are so cool) so we call the setQuantity method and pass it the parameter of 2. You can see that the total automatically updates itself in the new output:
Teddy Bear
2.99
3
8.97
Cool Sunglasses
12.99
25.98
This ends the basic Actionscript 2.0 lesson. Although this has been a simple walkthrough, this is a solid base that we wish to build upon. If you continue to the intermediate page, you will learn how to take the product you have created and place it in a shopping cart class.
Continue to intermediate page.
We would love to hear your feedback. Please email us as info AT ahfx DOT com.
Thursday, April 22, 2010
How to use the LoadVars Class--Login
Introduction
The LoadVars class allows developers to have a better control of the external loaded data. There are many reason to use the LoadVars class intead of the old deprecated loadvariables and loadvariablesNum
Brief Description of LoadVars
Both LoadVars and loadvariables allow flash to communicate with external data source, but LoadVars offers methods, being a class, which the loadvariables doesn't support, being a global function.
Some of the benefits if the LoadVars:
1) availability of internal methods, in order to control the received/sent data, such as onLoad. the onLoad method is executed automatically (this means you don't need to make a call) once data is received from flash. Moreover the same onLoad method has an internal argument which tell us if data has been received or not (Example of a 404 page)
2) methods such as getBytesLoaded and getBytesTotal. We can know how much data we are loading.
3) all the data sent or received from the LoadVars class remains into the class itself. This is a big differences between the loadvariables function in which all the data received were stored in the same scope of the function (thus overwriting all the data in the same level). This offers again a better control on the data received
1. the .load() method
Description:
the LoadVars.load() method loads variables from an external source in URL-encoded format. Flash will read the output of the page you're loading. Once all the data is loaded, all the variables will be stored into the LoadVars instance which makes the call.
Example of url-encoded output (the only which flash can read using loadvars):
nome=pietro&nick=lana&mail=pietro@flash-php.it
for more info about the format at macromedia.com
Returns:
- a boolean value into the onLoad handler, which means if data has been received correctly.
Usage:
A simple usage.
Let's create a simple php page like this:
$nome = "pietro" ;
$nick = "lana" ;
$mail = "pietro@flash-php.it" ;
/*
print the variables to the output in order to let flash read them
*/
$vars = "" ;
$vars .= "nome=" . $nome . "&" ;
$vars .= "nick=" . $nick . "&" ;
$vars .= "mail=" . $mail ;
echo $vars ;
?>
Note the usage of "&". if you have more than 1 variable to send to flash you must concatenate the variables with the "&" (like the urlencoding using the GET method in html). Each time flash will read the & char it will assume that the following word it's a variable name.
name=pietro&nick=lana
will prduce in flash:
name = "pietro";
nick = "lana";
If you need to use the "&" char inside a variable text (for example name=Alex&me) you must urlencode the "&" value into %26 (name=Alex%26me)
To lad variables in flash:
/* first create a new instance of the LoadVars object */
myVars = new LoadVars();
// call the load method to load my php page
myVars.load(" http://percorso/pagina.php ");
// once vars have been loaded, we will have these variables:
myVars.nome // "pietro"
myVars.nick // "lana"
myVars.mail // "pietro@flash-php.it"
Note:
- every variable received will be a string, this means that if you pass [ value=1 ] , once received we will have this:
myVars.value = "1;
- PAY attention of spaces before of after your code, it will be read!
for example if you write into a .txt file:
name=alex
&value=20
&num=1
you'll have in flash:
myVars.name = "alex\r\n";
myVars.value = "20\r\n";
myVars.num = "1";
Another important consideration.
When working with php files, if you make a .load calls in flash like this:
myVars.load("file.php");
you can't test your movie inside the flash IDE (CTRL+ENTER), this because in this way the php file won't be processed from your webserver and flash will read the source code of the php file, not the expected output!!
For this reason, while you're testing your movie inside the flash ide, use always absolute paths:
myVars.load("http://localhost/file.php");
where localhost is just an example, it can be your domain name
( this is a common error )
2. the .onLoad method
When all the variables has been loaded and parsed by the LoadVars object, the onLoad method is executed, if defined.
Let's use a simple trace action to see if our variables has been loaded..
myVars.onLoad = function( ){
trace("variables loaded");
}
An important thing to know is that the onLoad method is invoked from the onData method (another method of the LoadVars object) in this way:
this.onLoad(success);
As you can see it will pass the "success" parameter, a boolean (true/false) which means if the page is loaded correctly or not.
So, our code will be:
myVars.onLoad = function( success ){
if(success){
trace("variables loaded");
} else {
trace("Error loading page");
}
}
Now we can see how to access to the loaded variables.
myVars.onLoad = function (success) {
if (success) {
trace (" variables loaded ");
for( var prop in this ) {
trace (" key " + prop + " = " + this[prop]);
}
} else {
trace (" Error loading variables ");
}
}
Note the usage of "this" inside the myVars onLoad method. In fact while the onLoad method is executing everytime we use "this" we are refers to the myVars object itself, not the flash timeline !
All the variables are stored into the myVars object, so for this reason we need to use "this" to access to them.
But, if you want to access to the current timeline?
In order to refer to the timeline in which the onLoad methos is working you can do this:
myVars._path = this /* we are outside the onLoad method, to "this" is the current timeline */
myVars.onLoad = function (success) {
trace(this._path) // will output "_level0"
if (success) {
trace (" variables loaded ");
for( var prop in this ) {
trace (" key " + prop + " = " + this[prop]);
}
} else {
trace (" Error loading variables ");
}
}
Note:
a common error is try to access to the LoadVars properties when they are not already loaded. You can only access to its property only after the onLoad handler is executed, not before!
Example of wrong usage:
myVars._path = this;
myVars.onLoad = function(){
this._path.name = this.name
}
trace(myVars.name) // ERROR!!
correct usage:
myVars._path = this;
myVars.onLoad = function(){
this._path.name = this.name
trace(myVars.name) // CORRECT
}
3. method onData()
Description:
onData is automatically executed once external data is received, but not already parsed into property of the LoadVars object.
By default it is something similar to this:
LoadVarsObj.onData = function(stringa) {
if (stringa == undefined ) {
this.onLoad(false );
} else {
this.decode(stringa);
this.onLoad ( true );
}
}
For this reason it will pass to the onLoad method tha value true or false depending on the content of the data received, if no data has been recived this value will be false.
The decode method parse the url-encoded variables into readable property by flash.
You can overwrite this method with your own functions, but pay attention what you're doing.
4. send() method
Description:
send is used when you want to send some variables to an external page. It automatically converts the property of the LoadVars object into a url-encoded string
Returns:
Return always a true value, if the LoadVars object has at least one property to send, otherwise it returns false
Usage:
If we have a php page with a mysql query which expects nome, nickname and email as external variables:
if(!empty($_POST['nome']) && !empty($_POST['nick']) && !empty($_POST['mail']))
{
$conn = mysql_connect('host', 'user', 'pass') or die(mysql_error());
$db = mysql_select_db('db_name', $conn) or die (mysql_error());
$nome = $_POST['nome'];
$nick = $_POST['nick'];
$mail = $_POST['mail'];
$result = mysql_query("INSERT INTO nome_tabelle (nome, nick, mail)
VALUES ('$nome', '$nick', '$mail')") or die(mysql_error());
if($result)
{
echo "Everything is ok";
} else {
echo "Error writing data";
}
mysql_close($conn);
}
?>
In flash: first create a new instance of the LoadVars object, then assign to it all the properties to pass, and finally call the send method.
myVars = new LoadVars();
myVars.nome = "pietro";
myVars.nick = "lana";
myVars.mail = "pietro@flash-php.it";
myVars.send("http://localhost/pagina.php", "_blank", "POST");
the argument "_blank" tell flash in which target open the destination page "pagina.php". _blank means that a new page will be opened.
In the php page the variables are readed from the superglobal array $_POST, so we need to pass the variables using the method "POST", which is the 3rd argument passed n the send method.
5. sendAndLoad()
Description:
sendandLoad method combine the functionality of the methods load() and send(), it parse the properties of the LoadVars object in url-encode strings and send all to the external page, and will read the result output which this page send back as response.
We can specify which LoadVars object has to receive response. In most cases, use the same instance both for send and read data.
yVars = new LoadVars();
myVars.SendAndLoad(" http://percorso/pagina.php ", myVars, " POST ");
the arguments: page url, receiver object, sending method
Returns:
the same as the send method.
Usage:
For this example we will authenticate a user which send his login name and password from flash
This is the php page which check the login and password reading a db:
if(!empty($_POST['nick']) && !empty($_POST['password']))
{
$conn = mysql_connect('host', 'user', 'pass') or die(mysql_error());
$db = mysql_select_db('db_name', $conn) or die (mysql_error());
$nick = $_POST['nick'];
$pass = $_POST['password'];
$result = mysql_query("SELECT * FROM tabella_utenti
WHERE nick= '$nick' AND password = '$pass'") or die(mysql_error());
$num = mysql_num_rows($result);
if(num >0 )
{
echo "login=true&";
echo "msg=you're logged now";
} else {
echo "login=false&";
echo "msg=wrong user name or password";
}
mysql_close($conn);
} else {
echo "login=false&";
echo "msg=missing data";
}
?>
In flash we will have 2 input textfield with instance name "nickname" and "password",
flash form
and in the same level a button with this code:
on(release){
myVars = new LoadVars();
myVars.nick = nickname.text;
myVars.password = password.text;
myVars.onLoad = function(success){
if(success){
trace(this.msg);
if(this.login){
// ok, you're logged.. go to the page for
// registered users
}
} else {
trace("Error reading the php page");
}
}
myVars.SendAndLoad("http://percorso/pagina.php", myVars, "POST");
}
6. Other methods
The LoadVars object has also other methods:
.toString()
It will transoform all the properties of the LoadVars object into a string url-encoded. It is used by default from the send, sendAndLoad methods.
.decode()
It's the inverse method.. from an url-encoded string return well formatted properties.
.getBytesLoaded() & getBytesTotal()
Same usage as the getBytesLoaded() and getBytesTotal() from the MovieClip class. they return the bytes from an external loaded source.
The LoadVars class allows developers to have a better control of the external loaded data. There are many reason to use the LoadVars class intead of the old deprecated loadvariables and loadvariablesNum
Brief Description of LoadVars
Both LoadVars and loadvariables allow flash to communicate with external data source, but LoadVars offers methods, being a class, which the loadvariables doesn't support, being a global function.
Some of the benefits if the LoadVars:
1) availability of internal methods, in order to control the received/sent data, such as onLoad. the onLoad method is executed automatically (this means you don't need to make a call) once data is received from flash. Moreover the same onLoad method has an internal argument which tell us if data has been received or not (Example of a 404 page)
2) methods such as getBytesLoaded and getBytesTotal. We can know how much data we are loading.
3) all the data sent or received from the LoadVars class remains into the class itself. This is a big differences between the loadvariables function in which all the data received were stored in the same scope of the function (thus overwriting all the data in the same level). This offers again a better control on the data received
1. the .load() method
Description:
the LoadVars.load() method loads variables from an external source in URL-encoded format. Flash will read the output of the page you're loading. Once all the data is loaded, all the variables will be stored into the LoadVars instance which makes the call.
Example of url-encoded output (the only which flash can read using loadvars):
nome=pietro&nick=lana&mail=pietro@flash-php.it
for more info about the format at macromedia.com
Returns:
- a boolean value into the onLoad handler, which means if data has been received correctly.
Usage:
A simple usage.
Let's create a simple php page like this:
$nome = "pietro" ;
$nick = "lana" ;
$mail = "pietro@flash-php.it" ;
/*
print the variables to the output in order to let flash read them
*/
$vars = "" ;
$vars .= "nome=" . $nome . "&" ;
$vars .= "nick=" . $nick . "&" ;
$vars .= "mail=" . $mail ;
echo $vars ;
?>
Note the usage of "&". if you have more than 1 variable to send to flash you must concatenate the variables with the "&" (like the urlencoding using the GET method in html). Each time flash will read the & char it will assume that the following word it's a variable name.
name=pietro&nick=lana
will prduce in flash:
name = "pietro";
nick = "lana";
If you need to use the "&" char inside a variable text (for example name=Alex&me) you must urlencode the "&" value into %26 (name=Alex%26me)
To lad variables in flash:
/* first create a new instance of the LoadVars object */
myVars = new LoadVars();
// call the load method to load my php page
myVars.load(" http://percorso/pagina.php ");
// once vars have been loaded, we will have these variables:
myVars.nome // "pietro"
myVars.nick // "lana"
myVars.mail // "pietro@flash-php.it"
Note:
- every variable received will be a string, this means that if you pass [ value=1 ] , once received we will have this:
myVars.value = "1;
- PAY attention of spaces before of after your code, it will be read!
for example if you write into a .txt file:
name=alex
&value=20
&num=1
you'll have in flash:
myVars.name = "alex\r\n";
myVars.value = "20\r\n";
myVars.num = "1";
Another important consideration.
When working with php files, if you make a .load calls in flash like this:
myVars.load("file.php");
you can't test your movie inside the flash IDE (CTRL+ENTER), this because in this way the php file won't be processed from your webserver and flash will read the source code of the php file, not the expected output!!
For this reason, while you're testing your movie inside the flash ide, use always absolute paths:
myVars.load("http://localhost/file.php");
where localhost is just an example, it can be your domain name
( this is a common error )
2. the .onLoad method
When all the variables has been loaded and parsed by the LoadVars object, the onLoad method is executed, if defined.
Let's use a simple trace action to see if our variables has been loaded..
myVars.onLoad = function( ){
trace("variables loaded");
}
An important thing to know is that the onLoad method is invoked from the onData method (another method of the LoadVars object) in this way:
this.onLoad(success);
As you can see it will pass the "success" parameter, a boolean (true/false) which means if the page is loaded correctly or not.
So, our code will be:
myVars.onLoad = function( success ){
if(success){
trace("variables loaded");
} else {
trace("Error loading page");
}
}
Now we can see how to access to the loaded variables.
myVars.onLoad = function (success) {
if (success) {
trace (" variables loaded ");
for( var prop in this ) {
trace (" key " + prop + " = " + this[prop]);
}
} else {
trace (" Error loading variables ");
}
}
Note the usage of "this" inside the myVars onLoad method. In fact while the onLoad method is executing everytime we use "this" we are refers to the myVars object itself, not the flash timeline !
All the variables are stored into the myVars object, so for this reason we need to use "this" to access to them.
But, if you want to access to the current timeline?
In order to refer to the timeline in which the onLoad methos is working you can do this:
myVars._path = this /* we are outside the onLoad method, to "this" is the current timeline */
myVars.onLoad = function (success) {
trace(this._path) // will output "_level0"
if (success) {
trace (" variables loaded ");
for( var prop in this ) {
trace (" key " + prop + " = " + this[prop]);
}
} else {
trace (" Error loading variables ");
}
}
Note:
a common error is try to access to the LoadVars properties when they are not already loaded. You can only access to its property only after the onLoad handler is executed, not before!
Example of wrong usage:
myVars._path = this;
myVars.onLoad = function(){
this._path.name = this.name
}
trace(myVars.name) // ERROR!!
correct usage:
myVars._path = this;
myVars.onLoad = function(){
this._path.name = this.name
trace(myVars.name) // CORRECT
}
3. method onData()
Description:
onData is automatically executed once external data is received, but not already parsed into property of the LoadVars object.
By default it is something similar to this:
LoadVarsObj.onData = function(stringa) {
if (stringa == undefined ) {
this.onLoad(false );
} else {
this.decode(stringa);
this.onLoad ( true );
}
}
For this reason it will pass to the onLoad method tha value true or false depending on the content of the data received, if no data has been recived this value will be false.
The decode method parse the url-encoded variables into readable property by flash.
You can overwrite this method with your own functions, but pay attention what you're doing.
4. send() method
Description:
send is used when you want to send some variables to an external page. It automatically converts the property of the LoadVars object into a url-encoded string
Returns:
Return always a true value, if the LoadVars object has at least one property to send, otherwise it returns false
Usage:
If we have a php page with a mysql query which expects nome, nickname and email as external variables:
if(!empty($_POST['nome']) && !empty($_POST['nick']) && !empty($_POST['mail']))
{
$conn = mysql_connect('host', 'user', 'pass') or die(mysql_error());
$db = mysql_select_db('db_name', $conn) or die (mysql_error());
$nome = $_POST['nome'];
$nick = $_POST['nick'];
$mail = $_POST['mail'];
$result = mysql_query("INSERT INTO nome_tabelle (nome, nick, mail)
VALUES ('$nome', '$nick', '$mail')") or die(mysql_error());
if($result)
{
echo "Everything is ok";
} else {
echo "Error writing data";
}
mysql_close($conn);
}
?>
In flash: first create a new instance of the LoadVars object, then assign to it all the properties to pass, and finally call the send method.
myVars = new LoadVars();
myVars.nome = "pietro";
myVars.nick = "lana";
myVars.mail = "pietro@flash-php.it";
myVars.send("http://localhost/pagina.php", "_blank", "POST");
the argument "_blank" tell flash in which target open the destination page "pagina.php". _blank means that a new page will be opened.
In the php page the variables are readed from the superglobal array $_POST, so we need to pass the variables using the method "POST", which is the 3rd argument passed n the send method.
5. sendAndLoad()
Description:
sendandLoad method combine the functionality of the methods load() and send(), it parse the properties of the LoadVars object in url-encode strings and send all to the external page, and will read the result output which this page send back as response.
We can specify which LoadVars object has to receive response. In most cases, use the same instance both for send and read data.
yVars = new LoadVars();
myVars.SendAndLoad(" http://percorso/pagina.php ", myVars, " POST ");
the arguments: page url, receiver object, sending method
Returns:
the same as the send method.
Usage:
For this example we will authenticate a user which send his login name and password from flash
This is the php page which check the login and password reading a db:
if(!empty($_POST['nick']) && !empty($_POST['password']))
{
$conn = mysql_connect('host', 'user', 'pass') or die(mysql_error());
$db = mysql_select_db('db_name', $conn) or die (mysql_error());
$nick = $_POST['nick'];
$pass = $_POST['password'];
$result = mysql_query("SELECT * FROM tabella_utenti
WHERE nick= '$nick' AND password = '$pass'") or die(mysql_error());
$num = mysql_num_rows($result);
if(num >0 )
{
echo "login=true&";
echo "msg=you're logged now";
} else {
echo "login=false&";
echo "msg=wrong user name or password";
}
mysql_close($conn);
} else {
echo "login=false&";
echo "msg=missing data";
}
?>
In flash we will have 2 input textfield with instance name "nickname" and "password",
flash form
and in the same level a button with this code:
on(release){
myVars = new LoadVars();
myVars.nick = nickname.text;
myVars.password = password.text;
myVars.onLoad = function(success){
if(success){
trace(this.msg);
if(this.login){
// ok, you're logged.. go to the page for
// registered users
}
} else {
trace("Error reading the php page");
}
}
myVars.SendAndLoad("http://percorso/pagina.php", myVars, "POST");
}
6. Other methods
The LoadVars object has also other methods:
.toString()
It will transoform all the properties of the LoadVars object into a string url-encoded. It is used by default from the send, sendAndLoad methods.
.decode()
It's the inverse method.. from an url-encoded string return well formatted properties.
.getBytesLoaded() & getBytesTotal()
Same usage as the getBytesLoaded() and getBytesTotal() from the MovieClip class. they return the bytes from an external loaded source.
Transparent effect
onClipEvent(load){
this.stop();
this._alpha = 0;
var done:Boolean = false;
this.cF = 1;
}
onClipEvent(enterFrame){
if(this._alpha < 100 && !this.done){
this._alpha += 5;
}
if(this.done){
if(this._alpha <= 0){
this._x = -500;
_root.goNext = true;
}else{
this._alpha -= 5;
}
}
}
this.stop();
this._alpha = 0;
var done:Boolean = false;
this.cF = 1;
}
onClipEvent(enterFrame){
if(this._alpha < 100 && !this.done){
this._alpha += 5;
}
if(this.done){
if(this._alpha <= 0){
this._x = -500;
_root.goNext = true;
}else{
this._alpha -= 5;
}
}
}
Loading Bar
onClipEvent(load){
this.total = _root.getBytesTotal();
}
onClipEvent(enterFrame){
loaded = _root.getBytesLoaded();
current = int(loaded/this.total*100);
this.gotoAndStop(current);
if (loaded == total) {
_root.gotoAndStop(2);
}
}
this.total = _root.getBytesTotal();
}
onClipEvent(enterFrame){
loaded = _root.getBytesLoaded();
current = int(loaded/this.total*100);
this.gotoAndStop(current);
if (loaded == total) {
_root.gotoAndStop(2);
}
}
Context Menu Items
function goWeb(){
getURL("http://www.some.org",_blank);
}
MENU = new ContextMenu();
MENU.hideBuiltInItems();
MenuItem1 = new ContextMenuItem("copyrighted by ©", goWeb);
MenuItem2 = new ContextMenuItem("Visit our website @ www.some.org", goWeb);
MENU.customItems.push(MenuItem1);
MENU.customItems.push(MenuItem2);
_root.menu = MENU;
getURL("http://www.some.org",_blank);
}
MENU = new ContextMenu();
MENU.hideBuiltInItems();
MenuItem1 = new ContextMenuItem("copyrighted by ©", goWeb);
MenuItem2 = new ContextMenuItem("Visit our website @ www.some.org", goWeb);
MENU.customItems.push(MenuItem1);
MENU.customItems.push(MenuItem2);
_root.menu = MENU;
Check Input TextField
userName.text = "Enter Name";
var checkId = setInterval(func, 100);
var firstTime = true;
function func()
{
if(firstTime)
{
if(userName.text != "Enter Name")
{
userName.text = "";
clearInterval(checkId);
firstTime = false;
}
}
}
var checkId = setInterval(func, 100);
var firstTime = true;
function func()
{
if(firstTime)
{
if(userName.text != "Enter Name")
{
userName.text = "";
clearInterval(checkId);
firstTime = false;
}
}
}
Randomly choose the frame.
_global.frames = Array();
_global.getFirstFrame = function():Number
{
while(_global.frames.length > 0)
{
_global.frames.pop();
}
frameIdx = Math.floor(Math.random() * 4) + 1;
_global.frames.push(frameIdx);
return frameIdx;
}
_global.getNextFrame = function():Number
{
frameIdx = Math.floor(Math.random() * 4) + 1;
for(var i:Number = 0; i < _global.frames.length; i ++)
{
if(frameIdx == _global.frames[i])
{
frameIdx = Math.floor(Math.random() * 4) + 1;
i = 0;
}
}
_global.frames.push(frameIdx);
return frameIdx;
}
_global.getFirstFrame = function():Number
{
while(_global.frames.length > 0)
{
_global.frames.pop();
}
frameIdx = Math.floor(Math.random() * 4) + 1;
_global.frames.push(frameIdx);
return frameIdx;
}
_global.getNextFrame = function():Number
{
frameIdx = Math.floor(Math.random() * 4) + 1;
for(var i:Number = 0; i < _global.frames.length; i ++)
{
if(frameIdx == _global.frames[i])
{
frameIdx = Math.floor(Math.random() * 4) + 1;
i = 0;
}
}
_global.frames.push(frameIdx);
return frameIdx;
}
Sound Play
_global.sound = Array();
_global.playSound = function(soundName:String)
{
// for(var i:Number = 0; i < _global.soundNames.length ; i ++ )
// {
// if(_global.soundNames[i] == String("ticktock"))
// continue;
// _global.sound[_global.soundNames[i]].stop();
// _global.sound[_global.soundNames[i]] = null;
// }
//
if(_global.sound[soundName] != null &&
_global.sound[soundName] != undefined)
{
//_global.sound[soundName].stop();
}
else
{
//_global.soundNames.push(soundName);
_global.sound[soundName] = new Sound();
//_global.sound[soundName].stop();
_global.sound[soundName].attachSound(soundName);
}
_global.sound[soundName].start();
}
_global.stopSound = function(soundName:String)
{
if(_global.sound[soundName] != null &&
_global.sound[soundName] != undefined)
{
_global.sound[soundName].stop();
}
}
_global.playSound = function(soundName:String)
{
// for(var i:Number = 0; i < _global.soundNames.length ; i ++ )
// {
// if(_global.soundNames[i] == String("ticktock"))
// continue;
// _global.sound[_global.soundNames[i]].stop();
// _global.sound[_global.soundNames[i]] = null;
// }
//
if(_global.sound[soundName] != null &&
_global.sound[soundName] != undefined)
{
//_global.sound[soundName].stop();
}
else
{
//_global.soundNames.push(soundName);
_global.sound[soundName] = new Sound();
//_global.sound[soundName].stop();
_global.sound[soundName].attachSound(soundName);
}
_global.sound[soundName].start();
}
_global.stopSound = function(soundName:String)
{
if(_global.sound[soundName] != null &&
_global.sound[soundName] != undefined)
{
_global.sound[soundName].stop();
}
}
Processing Data From An Input Text Field
How to process data from an input text field:
* Select the "Text tool".
* Then in the properties panel:
o Set the text field type to "input".
* On stage create the text field and position.
* In the properties panel:
o Set the instance name of the text field to "number_input".
o Set the variable name to "input".
* Click on the stage area.
* In the properties panel:
o Set the text field type to "Dynamic"
* On stage create the text field and position.
* In the properties panel:
o Set the instance name of the text field to "number_output".
o Set the variable name to "output".
* In the timeline:
o Select the first frame of the "action" layer.
* Then open the actionscript panel and enter the following script:
enter_btn.onRelease = function(){
output = 5*input;
}
* Select the "Text tool".
* Then in the properties panel:
o Set the text field type to "input".
* On stage create the text field and position.
* In the properties panel:
o Set the instance name of the text field to "number_input".
o Set the variable name to "input".
* Click on the stage area.
* In the properties panel:
o Set the text field type to "Dynamic"
* On stage create the text field and position.
* In the properties panel:
o Set the instance name of the text field to "number_output".
o Set the variable name to "output".
* In the timeline:
o Select the first frame of the "action" layer.
* Then open the actionscript panel and enter the following script:
enter_btn.onRelease = function(){
output = 5*input;
}
Wednesday, April 21, 2010
Attaching a Bitmap – AS2
A common task that has changed drastically in ActionScript 3.0 is loading a library image via its linkageID into a BitmapData object and attaching it to a movieclip. In ActionScript 2.0, this can be done like so:
import flash.display.BitmapData
var bmp:BitmapData = BitmapData.loadBitmap("linkageID");
var img = createEmptyMovieClip("img",0);
img.attachBitmap(bmp,0);
import flash.display.BitmapData
var bmp:BitmapData = BitmapData.loadBitmap("linkageID");
var img = createEmptyMovieClip("img",0);
img.attachBitmap(bmp,0);
Image effect using fillRect
In ActionScript:
we start from the right side of the image (let's say the image is 380x380 px) and using an enterFrame function move 1 pixel per frame execution to the left.
At the first enterFrame execution we will copy all the pixel vertically in the _x position 380 of the original image, and apply the fill to a rectangle of 379 of width.
This will create the distortion effect.
But let's see the as code:
import flash.display.*
import flash.geom.*
/** define the variables used **/
var img:BitmapData
var cloned:BitmapData
var mc:MovieClip
var rect:Rectangle
var row:Number
var w:Number
var h:Number
var diff:Number
var pixelSize:Number = 1
// attach a bitmapData loading an image
// from the library
img = BitmapData.loadBitmap('image');
// and clone it
cloned = img.clone();
// getting the bitmapdata width and height
w = img.width;
h = img.height;
// create a new movieclip and attach the image
// to it
mc = this.createEmptyMovieClip("holder", 1);
mc.attachBitmap(img,1);
mc._x = 5
mc._y = 5
rect = new Rectangle()
row = -1
function fill(){
row += pixelSize
if(row < w){
diff = w - row
rect.width = diff
rect.height = pixelSize
for(var c = 0; c < h; c += pixelSize){
rect.y = c
img.fillRect(rect, cloned.getPixel32(diff, c))
}
} else {
delete this.onEnterFrame
}
}
function replay(){
delete this.onEnterFrame
row = -1
pixelSize = pSize.value
this.onEnterFrame = fill
}
pizelSize will define the width and height of the region to copy. This also can define a granular effect once the size is greater than 1 pixel.
Then first load the library image "image" into a bitmapdata object and also clone it into another bitmapdata object.
create a new flash.geom.Rectangle() which will be the first argument to pass to the fillRect() method
public fillRect(rect:Rectangle, color:Number) : Void
1. EnterFrame starts
2. move cursor towards left of 1 pixelSize
3. set the rectangle width to (image width - current cursor x)
4. for every pixel in height:
5. move the rectangle down of 1 pixel
6. get the color at the specified coordinate ( cursor x, y )
7. fill the rectangle with the same pixel color
3. A little modification.. another effect type
Now, modifying a little the above code you can do another kind of effect like this (granular):
and this is the fill() method modified:
function fill(){
for(row = 0; row < h; row += pixelSize){
for(col = 0; col < w; col += pixelSize){
rect.width = pixelSize*2
rect.height = pixelSize*2
rect.y = (row) - pixelSize
rect.x = (col) - pixelSize
img.fillRect(rect, cloned.getPixel32(col, row))
}
}
pixelSize -= 1
if(pixelSize < 2){
img = BitmapData.loadBitmap('image');
mc.attachBitmap(img,1);
delete this.onEnterFrame
}
}
we start from the right side of the image (let's say the image is 380x380 px) and using an enterFrame function move 1 pixel per frame execution to the left.
At the first enterFrame execution we will copy all the pixel vertically in the _x position 380 of the original image, and apply the fill to a rectangle of 379 of width.
This will create the distortion effect.
But let's see the as code:
import flash.display.*
import flash.geom.*
/** define the variables used **/
var img:BitmapData
var cloned:BitmapData
var mc:MovieClip
var rect:Rectangle
var row:Number
var w:Number
var h:Number
var diff:Number
var pixelSize:Number = 1
// attach a bitmapData loading an image
// from the library
img = BitmapData.loadBitmap('image');
// and clone it
cloned = img.clone();
// getting the bitmapdata width and height
w = img.width;
h = img.height;
// create a new movieclip and attach the image
// to it
mc = this.createEmptyMovieClip("holder", 1);
mc.attachBitmap(img,1);
mc._x = 5
mc._y = 5
rect = new Rectangle()
row = -1
function fill(){
row += pixelSize
if(row < w){
diff = w - row
rect.width = diff
rect.height = pixelSize
for(var c = 0; c < h; c += pixelSize){
rect.y = c
img.fillRect(rect, cloned.getPixel32(diff, c))
}
} else {
delete this.onEnterFrame
}
}
function replay(){
delete this.onEnterFrame
row = -1
pixelSize = pSize.value
this.onEnterFrame = fill
}
pizelSize will define the width and height of the region to copy. This also can define a granular effect once the size is greater than 1 pixel.
Then first load the library image "image" into a bitmapdata object and also clone it into another bitmapdata object.
create a new flash.geom.Rectangle() which will be the first argument to pass to the fillRect() method
public fillRect(rect:Rectangle, color:Number) : Void
1. EnterFrame starts
2. move cursor towards left of 1 pixelSize
3. set the rectangle width to (image width - current cursor x)
4. for every pixel in height:
5. move the rectangle down of 1 pixel
6. get the color at the specified coordinate ( cursor x, y )
7. fill the rectangle with the same pixel color
3. A little modification.. another effect type
Now, modifying a little the above code you can do another kind of effect like this (granular):
and this is the fill() method modified:
function fill(){
for(row = 0; row < h; row += pixelSize){
for(col = 0; col < w; col += pixelSize){
rect.width = pixelSize*2
rect.height = pixelSize*2
rect.y = (row) - pixelSize
rect.x = (col) - pixelSize
img.fillRect(rect, cloned.getPixel32(col, row))
}
}
pixelSize -= 1
if(pixelSize < 2){
img = BitmapData.loadBitmap('image');
mc.attachBitmap(img,1);
delete this.onEnterFrame
}
}
Subscribe to:
Posts (Atom)