kirupaForum

kirupaForum (http://www.kirupa.com/forum/index.php)
-   Flash ActionScript (http://www.kirupa.com/forum/forumdisplay.php?f=9)
-   -   ActionScript 3.0 Tip of the Day (http://www.kirupa.com/forum/showthread.php?t=223798)

oybrator 07-31-2006 12:51 PM

1.0 to 3.0 migration
 
I apologize in advance if this seems horribly out of place, but here it goes:

Would it make sense to start learning ActionScript 3.0 without knowing 2.0?

I am a fairly experienced ActionScript developer and I've been working with flash since version 3. When ActionsScript 2.0 arrived I sort of missed the point and went on developing with 1.0, after all it gets the job done and I'm already fluent in it.

Now I'm sweating a bit over having not kept up with the evolution and have decided I'm well overdue for catching up. I know a few basics of AS 2.0, but have never built anything with it. Should I make an effort to learn it and use it before progressing to 3.0 or would it be just as sensible to go straight to 3.0?

Any opinions with be greatly appreciated :-)

Thanks!

icio 07-31-2006 03:57 PM

If you're fluent in AS 1.0 it will only take a couple of days to learn what you need to do differently for AS 2.0

You've still got time before AS 3.0 is released with Flash 9 so I would take the time you have to catch up :)

oybrator 08-01-2006 02:35 AM

Quote:

Originally Posted by icio
If you're fluent in AS 1.0 it will only take a couple of days to learn what you need to do differently for AS 2.0

You've still got time before AS 3.0 is released with Flash 9 so I would take the time you have to catch up :)


So by that you mean that learning stuff that's "wrong" in terms of AS 3.0 is still the right way to go because it would be easier?

Thanks for your reply by the way!

icio 08-01-2006 02:43 AM

Yes... I think that's what I'm saying.

The thing is, with learning AS 3.0 you pretty much learn all you need to know that's different from between AS 2.0 and AS 1.0.

Learning AS 2.0 would more acustom you to how AS 2.0 defines variables etc. Also, if you learn AS 2.0 you're going to be a more experienced developer :)

AS 3.0 isn't going to be mainstream for a while yet... you could probably do both :)

theHollow 08-01-2006 02:46 AM

I'm guessing it is, but is AS 2.0 still going to be supported when AS 3.0 becomes mainstream?

senocular 08-01-2006 08:53 AM

Quote:

Originally Posted by theHollow
I'm guessing it is, but is AS 2.0 still going to be supported when AS 3.0 becomes mainstream?

Yes. AS3 represents a roadblock in terms of backwards compatibility. The only thing that can play AS3 is Flash 9. AS2 is essentially AS1 so even Flash Player 6 can play movies creates with AS2. Since the Flash player, as of 9, contains the VMs for both AS1/AS2 and AS3, AS1/AS2 will continue to be completely supported. And, really, AS1 will probably continue to be easier to use for designers since you have things like getURL("url string") and not navigateToUrl(new UrlReqest("url string")) and on events and things like that. But most importantly if that if you want to shoot for any earlier versions of the player, you'll be using AS1/AS2.

senocular 08-01-2006 03:56 PM

Number() Conversion No Longer Interprets Octals
 
In ActionScript 1 and 2, when you convert String values into their number equivalents using Number(), if the number was preceded by a "0", the value would be interpreted as an octal value (base 8) much in the same way a preceding "0x" means hex (base 16).
ActionScript Code:

// ActionScript 1 and 2
trace(Number("010")); // 8
 


This could often cause problems for 'normal' values that, more often than not, you'd rather stay decimal (base 10). In ActionScript 3, this is no longer the case. String values with preceding "0"s are no longer treated as octals (though "0x" still means hex).
ActionScript Code:

// ActionScript 3
trace(Number("010")); // 10
 


If you want to interpret a string as an octal, you would then use parseInt specifying a radix of 8
ActionScript Code:

trace(parseInt("010", 8)); // 8
 


senocular 08-01-2006 08:33 PM

Garbage Collection: Reference Counting & Mark and Sweep
 
Garbage collection (GC) is the automatic process in Flash that removes variables from memory when they are no longer needed. There are two processes that handle garbage collection in Flash, reference counting, and mark and sweep.

Reference counting is a process that keeps track of all the variables referencing an object in memory. When a new reference is created to point to an object, its reference count is updated and incremented by one.
ActionScript Code:

var a:Object = new Object(); // new Object in memory given reference count of 1
var b:Object = a; // Object now has reference count of 2
 



When ever there are no longer any references pointing to an object in memory, that object is purged from memory and permanently forgotten by the player.

ActionScript Code:

delete a; // Object has reference count of 1
delete b; // Object has reference count of 0, removed from memory
 


Note: remember, the delete operator only removes variable association, it does not delete objects in memory, the GC is responsible for that. Also delete will only work on non class member variables.

There are certain times when reference counting does not work. For example, if you have two objects that reference themselves but reference nothing else, they remain to have a reference count greater than 0 but they are in no way accessible to you, the programmer, so are in all other means as good as gone.
ActionScript Code:

var a:Object = new Object(); // reference(a) count 1
var b:Object = new Object(); // reference(b) count 1
a.b = b; // reference(b) count 2
b.a = a; // reference(a) count 2
delete a; // reference(a) count 1
delete b; // reference(b) count 1
 


Here both a and b are removed from the current scope so are no longer accessible. b is accessible from a and a is accessible from b, but since you can never get to a or b there's no way to get to b or a. These objects are as good as deleted from the programmer, however, they will remain in memory because they still contain a reference count greater than 0. This is where mark and sweep comes into play.

Mark and sweep is a process that scans all references and object from a base location (such as the root or stage scope) and marks each one found. All of those not found are inaccessible and are therefore deleted. Given the example with a and b, since a and b are no longer accessible from any object path derived from root, they are not marked and eventually get garbage collected.
Code:

[root] <- scan...
    [objectRef (marked)] <- scan...
          [objectRef (marked)] <- scan...
          [objectRef (marked)] <- scan...
    [objectRef (marked)] <- scan...
    [objectRef (marked)] <- scan...
...
[delete all objects not marked]

Mark and sweep is a more expensive process compared to reference counting so it takes longer and is performed less often. In fact, provided little or no activity in your movie, many frames could elapse before mark and sweep kicks in. What this means is that you could potentially have variables in memory for a long time after you assumed them to be gone. For objects that have actions associated with them, such as events coming off of enterFrame events, this could be something to be concerned about since those events could still operate after the object should technically be deleted. You should always make sure you "cleanup" your events for situations where they might remain in memory longer than you want.

oybrator 08-02-2006 02:51 AM

Quote:

Originally Posted by icio
Yes... I think that's what I'm saying.

The thing is, with learning AS 3.0 you pretty much learn all you need to know that's different from between AS 2.0 and AS 1.0.

Learning AS 2.0 would more acustom you to how AS 2.0 defines variables etc. Also, if you learn AS 2.0 you're going to be a more experienced developer :)

AS 3.0 isn't going to be mainstream for a while yet... you could probably do both :)


I'll take your word for it – I've allready started reading "Essential ActionScript 2.0" (Moock) for the second time and I'm enjoying it!

Thanks!

jeromeribot 08-02-2006 06:38 AM

how to make actionscript 3 play generated pcm wave data
 
Here's a little something our resident Chris came up with:


http://www.flashcodersbrighton.org/wordpress/?p=9


thought i'd inform


;)

Jerome

senocular 08-03-2006 09:31 AM

Weak References
 
If you want a reference to exist for an object that will not be counted towards the reference count used by the Garbage collector, then you can use a weak reference. Weak references are ignored by the reference counter and can exist even if the object is deleted.

You can't use weak references anywhere, however. There are only two places you can use weak references in ActionScript 3. One place is with Dictionary objects. The Dictionary constructor allows one optional parameter that specifies whether or not keys within the instance are weak references or not. False is the default value which means strong references. If you pass true, the Dictionary instance will use weak references
ActionScript Code:

var dict:Dictionary = new Dictionary(true); // use weak references as keys
 


If you do this for Dictionary instances, the keys you use to store values will not be counted towards that object's reference count.
ActionScript Code:

var obj:Object = new Object();
dict[obj] = true;
delete obj; // obj can be garbage collected since the dict reference isnt counted
 



The EventDispatcher's addEventListener is the other place you can specify weak references. addEventListener has a parameter that lets you specify the listener reference as being weak (since listeners internally require a reference to the object they are listening to).
ActionScript Code:

// addEventListener(type:String, listener:Function, useCapture:Boolean = false, priority:int = 0, useWeakReference:Boolean = false):void
addEventListener(MouseEvent.CLICK, clickHandler, false, 0 true); // use weak references
 


For addEventListener, the default is also false, using strong references, though it's good habit to use weak listeners to help with garbage collection.

senocular 08-04-2006 09:52 AM

Flash 9: BitmapData and Bitmaps from the Library
 
Flash 8 let you load bitmap information from the library using a linkage ID and the BitmapData.loadBitmap() method. This is no longer the case with Flash 9 and ActionScript 3. Now, as with timelines and movie clips in the library, Bitmaps are associated with classes. If you do not specify a specific class to be related to your bitmap in the library, you can name one which will be created automatically when publishing the SWF.

Classes associatated with bitmaps in the library are subclasses of BitmapData (flash.display.BitmapData). These are then instantiated as instances in ActionScript using the new keyword. As BitmapData instances, before being able to be seen on the screen, they would need to be associated with a Bitmap (flash.display.Bitmap) instance which is a display object capabale of being added to a display list (BitmapData instances cannot be added to display lists).

As an example, lets say you imported a bitmap of Rome in your library. In the linkage dialog for that bitmap, give it a class name of RomeImage - note that you don't have to create this class yourself; it will be created automatically. Then, to display it on the screen in ActionScript, use:

ActionScript Code:

// create instance of RomeImage bitmap data
var romeImageData:RomeImage = new RomeImage();

// create a bitmap instance that references the RomeImage instance
var romeImageBitmap:Bitmap = new Bitmap(romeImageData);

// add the new bitmap to the display list
addChild(romeImageBitmap);


cahlan 08-04-2006 02:57 PM

sound visualization
 
Quote:

Originally Posted by senocular
Using ActionScript 3 you can now obtain sound spectrum information from audio played through Flash. This lets you create visualizations like those seen in popular in media player applications. The class that provides this information is the SoundMixer class (flash.media.SoundMixer). It's computeSpectrum method (static) places sound spectrum information in a ByteArray instance which can then be used to generate a visualization.


FYI ...

There are some cool examples of this here: http://www.gotoandlearn.com/forum/viewtopic.php?t=3175

senocular 08-05-2006 11:50 AM

Changes in typeof
 
The typeof operator lets you determine the basic type of any value. Note that this does not give you actual class association information, but only provides a simplistic indication of the type of variable its used with. For more information regarding specific class relation, use instanceof, getQualifiedClassName, or describeType.

In ActionScript 1 and 2, typeof returned the following values:
  • boolean
  • function
  • movieclip
  • null
  • number
  • object
  • string
  • undefined

In ActionScript 3, typeof returns:
  • boolean
  • function
  • number
  • object
  • string
  • xml
  • undefined

Notice that MovieClip instances are, in AS3, no longer recognized by typeof. They are now seen as objects. Additionally, there is no null value (also seen as an object) and xml is seen as being of type xml.

The new number types in AS3, int and uint, when used with typeof both return number.

Also, primitive values (boolean, number, and string) created with their constructors and the new keyword are now recognized as those primitive types by typeof and not as objects as they were in AS1 and AS2.

ActionScript Code:

// AS1 & AS2
trace(typeof new XML()); // object

trace(typeof my_mc); // movieclip

trace(typeof null); // null

trace(typeof true); // boolean
trace(typeof 1); // number
trace(typeof ""); // string

trace(typeof new Boolean()); // object
trace(typeof new Number()); // object
trace(typeof new String()); // object
 



ActionScript Code:

// AS3
trace(typeof new XML()); // xml

trace(typeof my_mc); // object

trace(typeof null); // object

trace(typeof true); // boolean
trace(typeof 1); // number
trace(typeof ""); // string

trace(typeof new Boolean()); // boolean
trace(typeof new Number()); // number
trace(typeof new String()); // string

trace(typeof int(1)); // number
trace(typeof uint(1)); // number
 


senocular 08-06-2006 02:19 PM

getBounds() vs getRect()
 
Like ActionScript 1 and 2, ActionScript 3 has a getBounds() (flash.display.DisplayObject.getBounds()) method for determining the bounds of a movie clip (display object) in the coordinate space of any timeline. In ActionScript 3, however, getBounds has changed to return a Rectangle (flash.geom.Rectangle) instance instead of a generic object with the properties xMin, xMax, yMin, and yMax.

ActionScript 3 also adds an additional method similar to getBounds called getRect() (flash.display.DisplayObject.getRect()). The getRect() method works just like getBounds except it doesn't take into consideration strokes on shapes.

The following example shows the differences between the rectangle shape returned by getBounds and that returned by getRect.

ActionScript Code:

var sprite:Sprite = new Sprite();
sprite.graphics.beginFill(0x999999);
sprite.graphics.lineStyle(10, 0x333);
sprite.graphics.drawCircle(100, 100, 50);
sprite.graphics.endFill();
addChild(sprite);

addChild(createRectShape(sprite.getRect(this), 0xFF00FF));
addChild(createRectShape(sprite.getBounds(this), 0xFF0000));

function createRectShape(rect:Rectangle, color:uint):Shape {
    var rectShape:Shape = new Shape();
    rectShape.graphics.lineStyle(0, color);
    rectShape.graphics.drawRect(rect.left, rect.top, rect.width, rect.height);
    return rectShape;
}



Running the above script draws a circle with a stroke of 10 px with two rectangles around it, one which fits to the vector shape of the circle (getRect) and the other which fits to the bounds of the whole object including the stroke (getBounds).

The rectangle returned by getRect relates to width and height values associated with the display object (which doesn't account for strokes) while getBounds returns a rectangle associated with the visual boundaries of the display object. Note that filters are not accounted for in either method.

bodyvisual 08-06-2006 08:09 PM

god i'm so scared of as3 ok?

senocular 08-07-2006 08:00 AM

for..in and for each..in
 
ActionScript 3 has a new iteration statement: for each..in (for each..in). for each..in works much like for..in (for..in) execpt it loops through the values of an object rather than its keys. Example:

ActionScript Code:

var object:Object = new Object();
object.name = "senocular";
object.id = 2867;
object.isModerator = true;
for each (var value:* in object){
    trace(value);
}
/* Output:
true
2867
senocular
*/


Respectively, a for..in would look like:
ActionScript Code:

var object:Object = new Object();
object.name = "senocular";
object.id = 2867;
object.isModerator = true;
for (var key:String in object){
    trace(key + ": " + object[key]); // object[key] is value
}
/* Output:
isModerator: true
id: 2867
name: senocular
*/


Note that the key is not available in for each..in.

ActionScript 3 also maintains array element order (using numeric array indices) when using for..in and for each..in rather than basing order off of when the value was created as was the case in ActionScript 1 and 2. Example:
ActionScript Code:

var array:Array = new Array();
array[1] = 1;
array[0] = 2;
array[2] = 3;
for (var key:String in array){
    trace("array[" + key + "] = "+ array[key]);
}


Output AS 1 & AS 2:
Code:

array[2] = 3
array[0] = 2
array[1] = 1


Output AS 3:
Code:

array[0] = 2
array[1] = 1
array[2] = 3


This provices a more intuitive order when iterating through arrays with for..in and for each..in.

Note: To use the for each..in statement with an instance of a user-defined class, you must declare the class with the dynamic attribute.

senocular 08-09-2006 06:55 AM

Default Values for Function Parameters
 
ActionSript 3 now allows you to specify default values for your function's parameters. In doing so, that parameter then becomes optional and the default value assigned to the respective argument in the function call if a value is explicitly not provided.
ActionScript Code:

function method(required:String, optional:String = "default"):void {
    trace(required +" "+optional);
}
method("Hello"); // "Hello default"
 


You can only place parameters with default values after all required parameters. In other words you can't have
ActionScript Code:

// Incorrect:
function method(required:String = "default", optional:String):void { ...


since there would be no way for optional to be set without required having to be set as well.

senocular 08-09-2006 07:04 AM

Undetermined Number of Arguments With ...(rest)
 
Since ActionSript 3 checks argument count when functions are called you are not able to pass any number of arguments to any function like you could in ActionScript 1 or ActionScript 2. Instead, to allow for this, you need to use a new special kind of parameter called ...(rest) (Keyword: ...(rest)).

The ...(rest) parameter is a special parameter placed at the end of a parameter list in a function that specifies that there can be any number of additional arguments of any type passed into that function when its called. The form of the parameter is 3 periods followed by a keyword. When the function is called, the additional arguments are assigned to that keyword in the form of an array.
ActionScript Code:

function usingRest(required:Number, ... optionalArgs):void {
    trace(required); // 1
    trace(optionalArgs); // [2, 3, 4]
}
usingRest(1, 2, 3, 4);


senocular 08-09-2006 07:14 AM

arguments
 
As with ActionScript 1 and ActionScript 2, ActionScript 3 has an arguments (Top level arguments) object that is a special object created for each function call when it is executed in Flash. In ActionScript 3, however, there is no arguments.caller property. To get a reference to the caller, you must pass a reference to that function as an argument. The callee property still exists.
ActionScript Code:

function args(str:String, num:Number):void {
    trace(arguments);
}
args("a", 1); // ["a", 1]
 



Unfortunately, the arguments array does not exist when using the ...(rest) parameter meaning the arguments array can only be used when ...(rest) is not. This is something to consider if you are using ...(rest) but still want a reference to callee.

Increu 08-09-2006 11:59 PM

Hey Sen, when you run out of ideas, maybe you can talk about ByteArray, it would be really cool

gburks 08-10-2006 08:03 AM

external swf as cursor 'gets in the way'
 
1 Attachment(s)
RE: your tip of the day, "Detecting When the Mouse Leaves the Movie"

I noticed behavior that didn't exist in AS2 that now happens in AS3: When you use an externally loaded SWF to replace the mouse cursor, the loaded movie prevents the hit area from triggering if the movie is directly below the cursor.

I noticed this when trying to load an swf with animation. My buttons would return to the upState as the animation moved below the cursor, and again go back to the overState as the animation moved out of the way.

Attached is a modified version of your class that replaced the cursor. It includes a button on the stage and an animated externally loaded cursor. I left the real mouse pointer visible to demonstrate the "on-off" switching.

gburks 08-10-2006 07:54 PM

solution -
mouseEnabled = false; on the externally loaded movie.

senocular 08-11-2006 09:10 AM

Support for Namespaces
 
ActionScript 3 now supports namespaces. Namespaces in AS3 are similar to namespaces in XML and provide a way to separate code in to separate "spaces" or collections identifiable through a name (namespace). Namespaces in this respect act much like packages. In the same manner that packages allow you to have different classes with the same name in one application (only defined in different packages), namespaces allow you to have different methods with the same name in one class (defined in different namespaces). Though you may not have known it, chances are you've already been using namespaces. Predefined namespaces include public, private, protected, and internal.

When you use a namespace, you have to declare it just like you declare any other class member. Namespaces are declared using the namespace keyword (namespace Keyword). Once declared you can use it to separate members into different namespaces. Ex:
ActionScript Code:

package {
   
    public class UsingNameSpaces {
       
        public namespace company;
        public namespace individual;
       
        company var value:int = 10;
        individual var value:int = 2;
       
        public function UsingNameSpaces(){
        }
       
        company function showValue() {
        }
       
        individual function showValue() {
        }
    }
}


Two namespaces were used here, company and individual. They were used to defined a value variable and a showValue method - one for each namespace. Though they have the same names, since they are in different namespaces, they are allowed.

Additionally, namespaces can otionally be defined with a namespace uri when declared in the class:
ActionScript Code:

package {
   
    public class UsingNameSpaces {
       
        public namespace company = "http://www.example.com/company";
        public namespace individual = "http://www.example.com/individual";
       
        company var value:int = 10;
        individual var value:int = 2;
       
        public function UsingNameSpaces(){
        }
       
        company function showValue() {
        }
       
        individual function showValue() {
        }
    }
}


senocular 08-11-2006 09:10 AM

Namespaces: Name Qualifier Operator (::)
 
When you want to access a class member in a namespace, you need to reference that member through the namespace in which it was defined. One way to do this is through the name qualifier operator (name qualifier operator).

The name qualifier operator takes the form of two colons that connects the namespace with the member of the class you are trying to access that exists within that namespace, eg. namespace::member. Ex:
ActionScript Code:

package {
   
    public class UsingNameSpaces {
       
        public namespace company = "http://www.example.com/company";
        public namespace individual = "http://www.example.com/individual";
       
        company var value:int = 10;
        individual var value:int = 2;
       
        public function UsingNameSpaces(){
            company::showValue(); // traces 10
            individual::showValue(); // traces 2
        }
       
        company function showValue() {
            trace(company::value);
        }
       
        individual function showValue() {
            trace(individual::value);
        }
    }
}


Note that even though showValue is being called within the namespace, the namespace is still needed to reference variables (or other members) in namespaces used within the function body.

disobey design 08-11-2006 10:29 AM

Very interesting stuff on namespaces, Senocular, but I have a question:

How would you reference class members from outside the class?

I assume it would be like this:

Code:

var myObj = new UsingNameSpaces();
myObj.company::showValue();



Is that correct? Are the namespace declarations treated as any other class property?

senocular 08-11-2006 01:04 PM

Quote:

Originally Posted by disobey design
Very interesting stuff on namespaces, Senocular, but I have a question:

How would you reference class members from outside the class?

I assume it would be like this:

Code:

var myObj = new UsingNameSpaces();
myObj.company::showValue();



Is that correct? Are the namespace declarations treated as any other class property?


namespaces, as I have written them, aren't necessarily like properties - they're more like classes.

The code you have is correct, but will not work with the UseNameSpaces class as I have written it since the namespaces were defined in the class body. For your code to work, you would need to define the namespaces in the package body (in the same block the class is defined).
ActionScript Code:

package {
   
    public namespace company = "http://www.example.com/company";
    public namespace individual = "http://www.example.com/individual";
    public class UsingNameSpaces { ... }
}



There is also a way to define namespaces as properties but I will cover that later.

a.neuhaus 08-11-2006 01:06 PM

Tween in AS3
 
It might sound like a amenitie to developers, but I'm a designer so it is a bless to me.
What happened to it? All my attempts to import it return an error:

Code:

package{

    import mx.effects.Tween;
    import flash.display.MovieClip;
   
    public class Main extends MovieClip{


        public function Main(){
           
            var t:Tween = new Tween();
           
        }
    }
}


Error #1046: Type was not found or was not a compile-time constant: Tween.

Is there a way to overcome this missing class?
Or, is there a class in the new API with its functionality?

Thanks in advance.

senocular 08-11-2006 01:16 PM

this was addressed earlier in the thread ;)

matzo 08-11-2006 01:36 PM

I don't know if this really is the place, but many people already asked their as3 questions here, so here I go. I tried the alpha version from flash 9 with this code
Code:


import flash.display.*;
var Filter:GradientGlowFilter = new GradientGlowFilter(4.0, 90,[0x00FF00], [50], [3], 4.0, 4.0, 1, 1, "outer");
var Movie:MovieClip = new MovieClip();
Movie.graphics.lineStyle(1);
Movie.graphics.drawRect(10,10,100,100);
addChild(Movie);
Movie.filters=new Array(Filter);

Now, I've tested it and it worked.(Jiehaa!)
But, then I notices that I forgot to import flash.filters.*;
Though, it worked without any problem?
Is this a bug, or is this really the intend of Adobe.

(yeah you may have noticed that English is not at all my native language so.., sorry:p:mountie: )

senocular 08-11-2006 01:45 PM

in Flash 9 the classes inherent to Flash are automatically imported

senocular 08-12-2006 08:55 AM

dynamic is Not Inherited
 
Like ActionScript 2, ActionScript 3 allows you to create dynamic classes using the dynamic keyword (dynamic keyword). Dynamic classes are classes you can add properties to dynamically without needing to declare or define them within the class definition. An example of a dynamic class would be Array. When you create an Array instance, you can assign to it any variariable you want despite it not being within the Array class definiton.

In AS2, when you extended a class that was dyanmic, that subclass too became dynamic.
ActionScript Code:

// superclass.as
dynamic class superclass {
}

// subclass.as
class subclass extends superclass {
}

// main movie
var instance:subclass = new subclass();
trace(instance.anything); // ok since subclass inherited dynamic
 



This is no longer the case with AS3. Subclasses of dynamic classes are no longer dynamic unless specified as being dynamic themselves
ActionScript Code:

// superclass.as
package {
    dynamic class superclass {
    }
}

// subclass.as
package {
    class subclass extends superclass {
    }
}

// main movie
var instance:subclass = new subclass();
trace(instance.anything); // error, property not defined (not dynamic)
 


Increu 08-14-2006 05:39 AM

swap depths in as3
 
1 Attachment(s)
I dont know if i am doing it rigth, but i tryed this:
ActionScript Code:
var cr = new vv1();
addChild(cr);
cr.x = 30;
var c2 = new mc2();
addChild(c2);
c2.x = 40;
var c3 = new mc3();
addChild(c3);
c3.x = 70;
cr.y = 100;
c2.y = 110;
c3.y = 120;


var sortedItems:Array = new Array(cr, c2, c3);
function arrange():void {
sortedItems.sortOn("y", Array.NUMERIC);
var i:int = sortedItems.length;
while(i++){
if( getChildAt(i)!= sortedItems[i]){
setChildIndex(sortedItems[i],i);
}
}
}
arrange();



And flash says:RangeError: the supplied index is out of bounds

senocular 08-14-2006 08:57 AM

it should be while(i--)

Increu 08-14-2006 09:56 AM

Oh, now is working!I dont know why Its always that little things that catch me!
Thanks Sen!!

senocular 08-15-2006 05:28 AM

Creating a mouseWithin Event
 
There are times where you might want to have actions only run when the mouse is within a sprite or movie clip. Director's Lingo programing language has a mouseWithin event that facilitates this. Flash, however, has no such event. However, with ActionScript 3's event model, you can easily create your own.

A mouseWithin event is essentially an enterFrame event that only runs when the mouse is within or touching the display object in which its associated. So, in making your own, all you need to do is define an enterFrame event when the mouse enters the object and remove it when the mouse leaves the object. And yes, technically you could do this in ActionScript 1 and ActionScript 2, but it would mean using up event handlers like onRollOver and onEnterFrame which could interfere with other actions for your movie clip (since you can only have one per movie clip).

For ActionScript 3, implementing a mouseWithin event just means giving your sprite or movie clip class a few event handlers and setting up some listeners, e.g.
ActionScript Code:

// methods managing mouseWithin
private function addMouseWithin(event:MouseEvent):void {
    addEventListener(Event.ENTER_FRAME, mouseWithin);
}
private function removeMouseWithin(event:MouseEvent):void {
    removeEventListener(Event.ENTER_FRAME, mouseWithin);
}
private function mouseWithin(event:Event):void {
    dispatchEvent(new MouseEvent("mouseWithin"));
}

// in constructor
public function MySpriteClass() {
    addEventListener(MouseEvent.MOUSE_OVER, addMouseWithin);
    addEventListener(MouseEvent.MOUSE_OUT, removeMouseWithin);
}


With that, a mouseWithin event fires every frame whenever the mouse is within the sprite. To add listeners for it, just use:
ActionScript Code:

addEventListener("mouseWithin", mouseWithinHandler);


senocular 08-15-2006 05:37 AM

Prevent Overriding and Subclassing with final
 
The final keyword (Toplevel final keyword) is an attribute for classes and methods that lets you prevent overriding (methods) and subclassing (classes).

When a method is marked as final, no subclasses of that class can create a method of the same name that overrides that method. This ensures that when the method is called, it will always be the method marked final.
ActionScript Code:

final public function methodName() {
    // your statements here
}



Similarly, for classes, if a class is marked final, no subclasses can be created that extend that class.
ActionScript Code:

package{
    final public class ClassName {
        // your statements here
    }
}



Note: it is pointless to have methods marked as final in a class marked as final since that class cannot be extended. Since it cannot be extended, there would be no way for methods to be overridden as that only occurs within subclasses of the original class.

senocular 08-16-2006 08:14 AM

MXMLC: SWF Metadata Tag
 
If you're using MXMLC (the MXML and ActionScript 3 stand alone, command line compiler provided with the free Flex 2 SDK) to compile your ActionScript 3 SWFs, you can use the SWF metadata tag to set common properties for your movie. The SWF metadata tag supports 4 properties
  • width
  • height
  • frameRate
  • backgroundColor
Example:
ActionScript Code:

package {
    [SWF(width="500", height="450", frameRate="24", backgroundColor="#FFFFFF")]
    public class MyApp extends Sprite {

    }
}


When compiled, the above makes a SWF 500x450 in size with a background color of white and a framerate of 24.

senocular 08-18-2006 07:57 AM

Proxy Class
 
ActionScript 3 introduces a new class to take the place of ActionScript 1 and ActionScript 2's addProperty method and __resolve handler for objects. This class is the Proxy Class (flash.utils.Proxy).

In ActionScript 1 and ActionScript 2:
  • addProperty() - used to dynamically add a getter/setter property for an object or class. This dynamically created a variable that was set and whose value was retrieved through functions passed into the addProperty call.
  • __resolve - a handler that, when defined for an object, would be called when a property or method was accessed that did not exist for that object. This let you capture unresolved references from an object and react accordingly

In ActionScript 3 you create a class that extends Proxy to take advantage of all its features. They include
  • Capturing property setting
  • Capturing property getting
  • Capturing property checking (if exists)
  • Capturing property deletion
  • Capturing method calls
  • Capturing decendant access
  • Capturing attribute checking
  • Handling property iteration

Though these features hold a lot of advange over what was available with AS1 and AS2, there are some drawbacks to using Proxy:
  • Instance typing is limited since classes need to extend Proxy; you tend to have to rely on interfaces
  • You cannot have Proxy classes that inherit from classes that don't already inherit from Proxy
  • Display objects cannot be Proxy classes

Proxy classes are generally used for variable container classes that need extra the flexibility.

senocular 08-18-2006 08:09 AM

in Operator
 
The in operator (in operator) is a new operator in ActionScript 3 that is used to see if a value exists within an object. This is similar to hasOwnProperty but will also work for inherited values.
ActionScript Code:

trace("PI" in Math);         // true
trace("myProperty" in Math); // false
 



All times are GMT -7. The time now is 08:17 AM.

Powered by vBulletin Version 3.5.4
Copyright ©2000 - 2006, Jelsoft Enterprises Ltd.
Copyright 2004 - kirupa.com