PDA

View Full Version : ActionScript 3 Tip of the Day



Pages : 1 2 [3]

JBack
April 30th, 2008, 02:44 PM
Hi senocular and the rest of the crew here,

I am very impressed with the amount of information contained in this thread. Thank you all for answering a lot of my questions so far just from the reading/skimming I have been doing the last couple hours.

Here is my hurdle I am trying to leap..
I have a class stored in a directory that is assigned in the classpath of Flash


package
{
public class book
{
public function book(nameParam:String, priceParam:Number):void
{
var book_obj:Object = new Object();
book_obj.bName = nameParam;
book_obj.bPrice = priceParam;
}
}
}
Pretty simple, no real rocket science going on.
Within my flash *.fla file I have the following code.


stop();
import book;

var book1:book = new book("Confederacy of Dunces", 19.95);
var book2:book = new book("The Floating Opera", 10.95);

trace (book1.bName);
When I publish the flash file I receive the error:

1119: Access of possibly undefined property bName through a reference with static type book.My question is, how do I access properties of objects created by classes?
This may be a wide-open can of worms kind of question but I am having difficulty figuring out scope and namespace. At least I think that is where my problem lies.

Appreciate any help you all can give me.

sgtPeper
April 30th, 2008, 02:52 PM
When you create a new ActionScript 3 application/movie, you're working with a main timeline as the "root" of your application. This root that *you* as a developer are working with then gets added to the stage when your main timeline instance is instantiated. This instance represents the root that is a property of DisplayObject. It is your main timeline...

Dear Senocular; as a designer i found really interesting this entry and i would like to go deeper, because all the things i knew are not useful now with AS3.


My question is:
How can I reference the main timeline from inside a movie clip?
I used to do this a lot in order to animate things and not over load the flash payer with different animations at the same time.


My “old” technique work like this:
Inside a movie clip placed in the main timeline, -with a stop function in the same frame as the movie clip-, I inserted at the end of the movie clips animation this code:


_root.gotoAndStop(“label”);


Then, the main time line goes to the “label” keyframe, stops, and plays another movie clip animation, and so on.


I tried this with AS3, and used the keyword stage and nothing happens. What this thing works now? What property from what class I should call?


Some insights…
Thanks.

SgtPeper

magcius
April 30th, 2008, 04:08 PM
Enable Strict Mode so you can see the errors better.

Stage does not have gotoAndPlay/Stop, it is not a MovieClip. Nothing should happen. Instead, you should use the root object. However, root is also a DisplayObject, not a MovieClip. You somehow need to cast this object to be of type MovieClip, so that you can call gotoAndPlay/Stop. What you should do instead:



MovieClip(root).gotoAndPlay("label");

JBack
April 30th, 2008, 04:14 PM
Hi senocular and the rest of the crew here,

I am very impressed with the amount of information contained in this thread. Thank you all for answering a lot of my questions so far just from the reading/skimming I have been doing the last couple hours.

Here is my hurdle I am trying to leap..
I have a class stored in a directory that is assigned in the classpath of Flash


package
{
public class book
{
public function book(nameParam:String, priceParam:Number):void
{
var book_obj:Object = new Object();
book_obj.bName = nameParam;
book_obj.bPrice = priceParam;
}
}
}
Pretty simple, no real rocket science going on.
Within my flash *.fla file I have the following code.


stop();
import book;

var book1:book = new book("Confederacy of Dunces", 19.95);
var book2:book = new book("The Floating Opera", 10.95);

trace (book1.bName);
When I publish the flash file I receive the error:
My question is, how do I access properties of objects created by classes?
This may be a wide-open can of worms kind of question but I am having difficulty figuring out scope and namespace. At least I think that is where my problem lies.

Appreciate any help you all can give me.

Well I solved it myself. Your stunned silence at my ignorance was deafening.

What I didn't realize is that when I use the code...


var book1:book = new book("Confederacy of Dunces", 19.95);
I am actually making an instance of the book class and need to use the parent object book1 in my path to the properties.

So the class looks like this:


package
{
public class book
{

public var book_obj:Object = new Object();

public function book(nameParam:String, priceParam:Number):void
{
book_obj.bName = nameParam;
book_obj.bPrice = priceParam;
}
}
}
And my first frame in my flash document looks like:


stop();
//import player;
import book;
//import quizinput;

var book1:book = new book("Confederacy of Dunces", 19.95);
var book2:book = new book("The Floating Opera", 10.95);

trace (book1.book_obj.bName);
And when I run it, it comes back with "Confederacy of Dunces".
Sorry for wasting space with the post, guess I just needed to talk to myself for a bit.

magcius
April 30th, 2008, 04:25 PM
Couple Pro Tips (I'm going to explain this in code):


package {

// Import Statements here if necessary.
// Start with uppercase letter, use UpperCaseForClassNamesLikeThis.
public class Book {

// Use instance variables, and try not to use prefixes for variable names.
// Put instance variable declarations before the constructor,
// except for "_" for private/protected variables where
// there is a property (getter/setter).
protected var _name:String;
public var price:Number;

// I always put :void after my constructors (which is incorrect, but it's not picky).
// Standard rule is that you don't put "Param" after parameter names;
// make it almost always the same as the instance variable.
public function Book(name:String, price:Number):void {
// Standard constructor. It assigns instance variables
// to the values in the arguments.
this.name = name;
this.price = price;
}

// Getters/Setters. I don't tend to use them unless I need to.
// Reasons for using them are things like read/write-only properties,
// and complicated logic in the setter. This is a read-only property.
public function get name ( ):String { return _name; }

}
}

JBack
April 30th, 2008, 04:37 PM
Much appreciated Magcius, I will definitely put those to good use.
I haven't done a lot of "class-work" but I am starting to like it.

Any other pearls you can drop at my feet I would be grateful.
I'm never one to turn down advice and tips.

Felixz
May 1st, 2008, 05:28 AM
there is one char missing
public function Book(name:String, price:Number):void {
// Standard constructor. It assigns instance variables
// to the values in the arguments.
this._name = name;//here
this.price = price;
}

Sentientv2
May 5th, 2008, 02:55 PM
That get keyword works only when you compile with AS2, correct? It throws the error (1024: Overriding a function that is not marked for override.).

I always use accessor(get) and modifer(set) functions to prevent inadvertently changing data from another class. I am just seriously getting into actionscript in AS3, so I didn't even know this was available when I used 2. As I said previously, if you don't use accessor and modifiers and your class variables are not private, then you're opening up the chance that you or someone working with you can alter another classes data in an indirect fashion.

My recommendation is if you feel the need to use prefixes, then perhaps instead of bName you would use strName so you know that it is of the type String. I would use the "i" prefix in "iCount" to denote an int, and so on.

jawele
May 8th, 2008, 08:29 AM
Hi all!

first of all thank you very much senocular for your helpful tips!
they are always a great source for me.

I have tested the example of the mouseChildren, but I guess there's a typo since I got exactly the opposite... from the quote below.



mouseChildren = true; output

spriteButton
mouseChildren = false; output

spriteGraphics

rosielarose
May 12th, 2008, 02:43 PM
Re: For loaded SWFs, the stage properties of its DisplayObject instances will reference the same stage as that referenced in the SWF that loaded it; there can be only one stage. For loaded SWFs, however, the root property will reference that loaded SWF's root, or its main timleine instance, not the root of the SWF that did the loading.

------------------------------------------------

Are you sure about this? From the loaded swf, I'm seeing its displayObject.stage.url and displayObject.stage.loaderURL both equal to the loaded swf's info, NOT the loader! The .root properties are the same as well. This is true whether the loaded swf is in the same domain or not. What if the loaded swf is put into a unique ApplicationDomain (in the system domain), as opposed to the same or a child application domain?

Any insight would be incredibly helpful...

lestat2411
May 13th, 2008, 11:57 AM
The ActionScript virtual machine that runs ActionScript 3 code (AVM2) is completely different from the ActionScript virtual machin that runs ActionScript 1 and ActionScript 2 code (AVM1). Because of this, you cannot call commands in an AVM1 movie from and AVM2 movie or vise versa. The virtual machines just are not compatible in that respect and mostly run in their own kind of shell that allows it to only interact with code being played back in that same virtual machine. What that boils down to is that ActionScript 3 cannot talk to AS1 or AS2 - at least not directly.

One thing these two virtual machines have in common is their implementation of LocalConnection. Both virtual machines deal with local connections in essentially the same way - enough that local connections in AVM1 can receive events from AVM2 and vise versa. So should you come into a situation where you would need a movie published in ActionScript 3 to communicate with a movie published in ActionScript 1 or 2, using local connection is the way to go.


LocalConnection AS2 (http://livedocs.macromedia.com/flash/8/main/00002338.html)
LocalConnection AS3 (flash.net.LocalConnection) (http://livedocs.macromedia.com/flex/2/langref/flash/net/LocalConnection.html)


Example:
ActionScript Code:

// ActionScript 2 file, AS2animation.fla
// one movie clip animation named animation_mc on the timeline

// local connection instance to receive events
var AVM_lc:LocalConnection = new LocalConnection();

// stopAnimation event handler
AVM_lc.stopAnimation = function(){
    animation_mc.stop();
}

// listen for events for "AVM2toAVM1"
AVM_lc.connect("AVM2toAVM1");



ActionScript Code:

// ActionScript 3 file, AS3Loader.fla

// local connection instance to communicate to AVM1 movie
var AVM_lc:LocalConnection = new LocalConnection();

// loader loads AVM1 movie
var loader:Loader = new Loader();
loader.load(new URLRequest("AS2animation.swf"));
addChild(loader);

// when AVM1 movie is clicked, call stopPlayback
loader.addEventListener(MouseEvent.CLICK, stopPlayback);

function stopPlayback(event:MouseEvent):void {
    // send stopAnimation event to "AVM2toAVM1" connection
    AVM_lc.send("AVM2toAVM1", "stopAnimation");
}




The AS3 movie loads the AS2 movie into a Loader instance and places it on the screen. As it plays, the user can click the animation which calls stopPlayback sending the "stopAnimation" event to the local connection named "AVM2toAVM1". The AS2 movie is then able to receive that event in its stopAnimation event handler and tell the animation_mc clip to stop.


I am having a problem with as3 talking to as2 after the initial as2 swf is loaded. Using this example, the first swf comes in and can be controlled just fine. However, if I load a second swf into the AS3 player, it no longer can be controlled. So basically what I need to figure out is how to load multiple as2 swfs into a as3 player. We have a bunch of content which was developed in as2 that we do not want to rewrite at this time. Is there a way to accomplish this.

P.S. The weirdest thing is I put a trace statement in the first as2 swf and after I have unload this clip and loaded the next as2 swf, the trace from the original swf can still be called meaning I believe its removed from the display list but not out of memory. Any clues would be greatly appreciated. I am playing around with gskinner swfbridge right now but haven't found a solution using this either. Thanks in Advance.

Stat

coolheart
May 14th, 2008, 02:40 AM
If my swf file contains a textbox, on some background, how to insert a text message like hello into that text box.




You can pass variables to SWF files in the object/embed code used to display a SWF in HTML. You can do this two ways, one using URL variables (query string) at the end of the SWF path, or through the FlashVars property.

<!-- URL Variables -->
<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0" width="640" height="500" align="middle">
<param name="allowScriptAccess" value="sameDomain" />
<param name="movie" value="flashMovie.swf?myVar=1" />
<param name="quality" value="high" />
<param name="bgcolor" value="#EFF7F6" />
<embed src="flashMovie.swf?myVar=1" quality="high" bgcolor="#EFF7F6" width="640" height="500" align="middle" allowScriptAccess="sameDomain" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" />
</object>
<!-- FlashVars -->
<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0" width="550" height="400" align="middle">
<param name="allowScriptAccess" value="sameDomain" />
<param name="movie" value="flashMovie.swf" />
<param name="quality" value="high" />
<param name="bgcolor" value="#FFFFFF" />
<param name="FlashVars" value="myVar=1" />
<embed src="flashMovie.swf" FlashVars="myVar=1" quality="high" bgcolor="#FFFFFF" width="550" height="400" align="middle" allowScriptAccess="sameDomain" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" />
</object>In ActionScript 2, these variables were simply defined as variables in _root. This has changed for ActionScript 3. Now these variables are accessible in a parameters object located in the root loaderInfo object.

Given the HTML embed code above, you would access the myVar property using:
ActionScript Code:

root.loaderInfo.parameters.myVar;

log2e
May 14th, 2008, 05:21 AM
Easing Functions in Flash CS3 / Flex 3 SDK

Tutorials on TweenLite or TweenMax often rely on the easing functions that come with the Flash CS3 IDE. These functions are contained in the package fl.motion.easing. All classes under the package name fl are specific to Flash CS3 and are not available in the free Flex 3 SDK. If you use the Flex 3 SDK you have to import your easing functions from the package mx.effects.easing. So any time you see an import statement like this

import fl.motion.easing.*;

you should be able to replace it with

import mx.effects.easing.*;

and get the same functionality.

kBisk
May 20th, 2008, 09:45 AM
In previous versions of ActionScript, there were a couple of classes who had the capability of loading external text, namely LoadVars and XML. The loading responsibilities of these classes has moved to one single class in ActionScript 3, URLLoader (flash.net.URLLoader (http://livedocs.macromedia.com/flex/2/langref/flash/net/URLLoader.html)). This class is a lot like LoadVars. The big difference is that it is used for XML since the responsibility of loading XML from an external source has been removed from the XML class. Instead, you would load the text with URLLoader and then give that text to an XML object for parsing.

Like LoadVars, URLLoader has a load() method that is used to load text from an external source. This accepts 1 argument, a URLRequest instance (NOT a URL string). You can then use events from URLLoader to determine when the loading is complete. When complete, the text loaded is available in the data property of URLLoader.

Example:
ActionScript Code:

var loader:URLLoader;
// ...
loader = new URLLoader();
loader.addEventListener(Event.COMPLETE, xmlLoaded);

var request:URLRequest = new URLRequest("file.xml");
loader.load(request);
//...
function xmlLoaded(event:Event):void {
&nbsp;&nbsp;&nbsp;&nbsp;var myXML:XML = new XML(loader.data);
&nbsp;&nbsp;&nbsp;&nbsp;//...
}




What event on URLLoader catches if the file does not load / does not exist?

Found the answer. Using a try/catch was also an option, but this event also works:

IOErrorEvent.IO_ERROR

project1.exe
May 27th, 2008, 07:52 AM
Hi,

I have a "u" and "v" variables and i do this for example...

var u:URLRequest = new URLRequest("www.google.com");
var v:URLVariables = new URLVariables("q=hehe");

u.data = v;

trace(u.url);

how do i get it so it will trace "www.google.com?q=hehe"

WestCoast101
May 30th, 2008, 07:31 PM
Thanks for the duplicateMovieClip package... As a relatively new AS3 student, can you direct me to an explanation of the options for the -- var targetClass:Class = Object(target).constructor; -- ? I apprecate that you can not instantiate the DisplayObject class.

In addition, although I have the AS3 Bible for reference, can you suggest other texts? I used Russell Chun's AS3 book effectively this Semester in my AS3 class.

delfeld
June 3rd, 2008, 11:22 AM
It's a good idea to make sure that the stage exists before working with it:


if (stage)
{
trace("stageWidth: " + stage.stageWidth + " stageHeight: " + stage.stageHeight);
stage.frameRate = stage.frameRate + 100;
}

log2e
June 4th, 2008, 12:24 PM
Configuration files often contain Boolean parameters for enabling or disabling features in an application or website. This way non-programmers can easily customize a complex system. But what if someone uses another word than “true” (for example, “1″, “yes”, “y”, “on”)?

In order to make my Flash/Flex apps less error-prone, I usually run all Boolean values from external configuration files through a converter. It’s a simple class with a single static method:


package
{
public class BooleanConverter
{

public static const TRUE_VALUES:Array = [ "1", "true", "yes", "y", "on", "enabled" ];

public static function makeBoolean( val:* ):Boolean
{
var str:String = String( val ).toLowerCase();

for ( var i:int = 0; i < BooleanConverter.TRUE_VALUES.length; i++ )
{
if ( str == BooleanConverter.TRUE_VALUES[i] )
{
return true;
}
}
return false;
}

}
}

Keyston
June 7th, 2008, 12:18 AM
Configuration files often contain Boolean parameters for enabling or disabling features in an application or website. This way non-programmers can easily customize a complex system. But what if someone uses another word than “true” (for example, “1″, “yes”, “y”, “on”)?

In order to make my Flash/Flex apps less error-prone, I usually run all Boolean values from external configuration files through a converter. It’s a simple class with a single static method:


package
{
public class BooleanConverter
{

public static const TRUE_VALUES:Array = [ "1", "true", "yes", "y", "on", "enabled" ];

public static function makeBoolean( val:* ):Boolean
{
var str:String = String( val ).toLowerCase();

for ( var i:int = 0; i < BooleanConverter.TRUE_VALUES.length; i++ )
{
if ( str == BooleanConverter.TRUE_VALUES[i] )
{
return true;
}
}
return false;
}

}
}



package
{
public class BooleanConverter
{

public static const TRUE_VALUES:Array = [ "1", "true", "yes", "y", "on", "enabled" ];

public static function makeBoolean( val:* ):Boolean
{
var str:String = String( val ).toLowerCase();

return (BooleanConverter.TRUE_VALUES.indexOf(str)!=-1)?true:false;

}

}
}

Thought i would post an optimized version

NickZA
June 9th, 2008, 05:34 PM
Hi

I'm currently trying to use a faux-abstract Singleton class to derive a couple of subclasses from.

The Singleton method I'm using is one of the many which uses a static function getInstance() to return the static var holding the singleton instance.

But it seems I'm unable to use getInstance() in the derived classes. I read elsewhere that "static methods and variables don’t exist within the inheritance chain of the class in AS3".

Is this why I cannot use getInstance() in the derived class? Is there a workaround?

Thanks.

-Nick



Overriding a method of a class means redefining a method for a class which would otherwise be inherited. The new method is then used in place of the inherited one (though the inherited method can still be invoked using super).

For ActionScript 3, when you override a method or property of a superclass, you need to use the override attribute with your new method. This specifies that the member you are creating is overriding that which would otherwise be inherited. If you do not use override with a method that already exists in a superclass, an error is thrown at compile time.

Ex:
ActionScript Code:

package {
&nbsp;&nbsp;&nbsp;&nbsp;import flash.display.*;
&nbsp;&nbsp;&nbsp;&nbsp;class MySprite extends Sprite {

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;private var children:Array = new Array();

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;public function MySprite() {
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;public override function addChild(child:DisplayObject):DisplayObject {
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;children.push(child);
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;super.addChild(child);
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return child;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}
&nbsp;&nbsp;&nbsp;&nbsp;}
}



Since addChild exists in the Sprite superclass, the override attribute is needed to successfully define the new addChild method which also adds the child passed to a children array.

Note that the method signature needs to match that of the overriden method

Override works with both normal class methods as well as getter/setter methods (properties), but it will not work with any of the following:

Variables
Constants
Static methods
Methods that are not inherited
Methods that implement an interface method
Inherited methods that are marked as final in the superclass


Also be aware that override is not needed for methods inherited directly from the Object class. These include:

hasOwnProperty
isPrototypeOf
propertyIsEnumerable
setPropertyIsEnumerable
toString
valueOf

These methods are added dynamically and are not part of the actual class definition. The override keyword is to be used only with methods which are part of a class's original definition.

However, if extending a class which uses a method above as part of its defnition, the override keyword is required. For example, if you are extending Object, you do not need to use the override keyword for the toString method. But, if you extend the Sprite class, you will need to override toString since the Sprite class has its own unique toString which is part of its class definition.

Krilnon
June 9th, 2008, 05:38 PM
Is this why I cannot use getInstance() in the derived class?

Yes.


Is there a workaround?

Yes, just define a new version of getInstance on your subclasses.

NickZA
June 9th, 2008, 05:43 PM
Damnit that was the fastest response I've ever seen. I was about to go to bed because of this problem, but now... ;)

Thanks Krilnon!


Yes.



Yes, just define a new version of getInstance on your subclasses.

delfeld
June 10th, 2008, 11:06 AM
The [SWF] metadata tag for AS3.0 has these params:

[SWF
width="#"
height="#"
widthPercent="#"
heightPercent="#"
scriptRecursionLimit="#"
scriptTimeLimit="#"
frameRate="#"
backgroundColor="#"
pageTitle="<String>"
]

Please see the comment at the bottom of this page:

http://livedocs.adobe.com/flex/3/html/help.html?content=metadata_3.html

NickZA
June 17th, 2008, 02:17 PM
Hi

Is there any way to pass arguments into the document class? I'm guessing no?

-Nick

johnlouis
June 19th, 2008, 09:34 AM
ActionScript 3 no longer has a duplicateMovieClip method for MovieClip instances (or any DisplayObject instances). Instead, it's suggested that you just create a new instance of the display object you wish to duplicate using its constructor. This, however, is not the same as duplicateMovieClip, and, really, is more like using AS1 and AS2's attachMovieClip. For a more accurate representation of duplicateMovieClip in AS3, consider the following function:

package com.senocular.display {

import flash.display.DisplayObject;
import flash.geom.Rectangle;

/**
* duplicateDisplayObject
* creates a duplicate of the DisplayObject passed.
* similar to duplicateMovieClip in AVM1
* @param target the display object to duplicate
* @param autoAdd if true, adds the duplicate to the display list
* in which target was located
* @return a duplicate instance of target
*/
public function duplicateDisplayObject(target:DisplayObject, autoAdd:Boolean = false):DisplayObject {
// create duplicate
var targetClass:Class = Object(target).constructor;
var duplicate:DisplayObject = new targetClass();

// duplicate properties
duplicate.transform = target.transform;
duplicate.filters = target.filters;
duplicate.cacheAsBitmap = target.cacheAsBitmap;
duplicate.opaqueBackground = target.opaqueBackground;
if (target.scale9Grid) {
var rect:Rectangle = target.scale9Grid;
// WAS Flash 9 bug where returned scale9Grid is 20x larger than assigned
// rect.x /= 20, rect.y /= 20, rect.width /= 20, rect.height /= 20;
duplicate.scale9Grid = rect;
}

// add to target parent's display list
// if autoAdd was provided as true
if (autoAdd && target.parent) {
target.parent.addChild(duplicate);
}
return duplicate;
}
}
As you can see, this function (duplicateDisplayObject) takes care of making sure a duplicated instance also retains all the information retained by duplicateMovieClip such as transformation, filters, chaching as bitmap, etc.

Note: There is currently a bug in Flash Player 9 that causes incorrect values to be returned from the scale9Grid property of display objects. This function compensates for that but may need to be edited should this bug be fixed.

Usage:

import com.senocular.display.duplicateDisplayObject;

// create duplicate and assign to newInstance variable
// using true for autoAdd automatically adds the newInstance
// into the display list where myOldSprite is located
var newInstance:Sprite = duplicateDisplayObject(myOldSprite, true);
newInstance.x += 100; // shift to see duplicate

The only thing duplicateMovieClip does that this does not is copy dynamic drawing information. Currently, the graphics object in display objects cannot be duplicated so there is no way to obtain that information for duplicates in duplicateDisplayObject.

i'm having problems with this method.. i have a movieclip I created on the stage, and I tried using this function on it, but I don't see any duplicated movieclip..
the code is on the timeline..


var temp:MovieClip = duplicateDisplayObject(mc, true) as MovieClip;
temp.x += 100;
I also tried duplicating a dynamically drawn Sprite (through graphics property), and like what the quote above said, i don't see anything..

Felixz
June 20th, 2008, 08:21 AM
addChild(temp)

johnlouis
June 20th, 2008, 10:55 AM
^i've set the second parameter to 'true', so it should automatically addChild, but I've also tried setting it to 'false' and doing it myself, but nothing. I'll try again.. thanks.

panopticon_
July 15th, 2008, 03:46 AM
i already posted a thread but my issue is very urgent .. i have to finish this project :(

so here we go again, mabye someone can help me out a bit:

http://www.kirupa.com/forum/showthread.php?t=303687

padlock12
July 19th, 2008, 10:37 PM
Any Tip for today?

senocular
July 29th, 2008, 10:33 AM
^i've set the second parameter to 'true', so it should automatically addChild, but I've also tried setting it to 'false' and doing it myself, but nothing. I'll try again.. thanks.

graphics drawings are not copied. An api for allowing this was only made available in Flash Player 10: Graphics.copyFrom();

blovas
August 5th, 2008, 11:17 AM
I am having the same error occur that has been provided in detail in this thread. Has anyone responded with a solution? I hope so and hoping someone will provide the answer. I have searched every where on the web and cannot find anything to help.

Thanks,
Brad

blovas
August 5th, 2008, 11:19 AM
Has anyone responded to your question? Thank you, Brad

blovas
August 5th, 2008, 11:24 AM
TypeError: Error #1009: Cannot access a property or method of a null object reference.
at fl.video::VideoPlayer/http://www.adobe.com/2007/flash/flvplayback/internal::doAutoResize()
at flash.utils::Timer/_timerDispatch()
at flash.utils::Timer/tick() [/php]If I just keep plowing through in debug the video will play and everything is fine. This project is just a POC so I am not so concerned about fixing the error just yet but is there a way to catch it and trace it so it won't show up for the client? Here is the relevant code:

eg19689
August 11th, 2008, 11:50 AM
cool tip!

mathot
August 12th, 2008, 06:24 AM
senocular, it's people like you that keep my faith in the human race. Thanks for your sterling efforts, they're a huge help to me and I'm sure they'll help the many thousands of other people who Google random bits of AS3 code/queries and consistently end up in this thread.

Just so you know, I've probably Google'd 40-50 tidbits relating to AS3 in the last couple of days and ended up here in this thread a good 90% of the time with the exact answer I was after.

WearDark
August 15th, 2008, 11:41 AM
Senocular:

I'm building a project that uses the HTML embed values for width and height to automatically adjust my SWF's size at run-time and Im having a bit of an issue.

On very rare occasions I'll grab stage.stageWidth from the main timeline (so I can use it to layout components on the stage) and I'll receive a value of 0. Unfortunately from that point onward, all of my components are referencing an incorrect value and the SWF does dot display properly. Im wondering if there is any way for me to determine when the stage (or perhaps its the root?) has been fully initialized (i.e. contains the proper values.)

I've tried using Event.ADDED_TO_STAGE but the event never fires (because it would fire before the code executes to actually add the listener?) I've also looked at your StageDetection class to no avail. Beyond that I tried accessing the width and height properties of this.root.loaderInfo but they seem to contain static values from the original SWF file and are not affected by the embed code values.

The only solution I can come up with currently is to set a timeout and wait a few seconds before using the values or polling the variables and waiting for them to contain appropriate values.

Is there a better solution to my problem than that? Are there any events that I can listen for that will guarantee me that the stage contains the values I need?

Thanks.

P.S Re-creating the issue is difficult, I've used Firebug with ExternalInterface to log values so when my SWF is on the webserver I can find out more about the error.

Hissam
August 21st, 2008, 02:05 AM
hii guys


I'm all new to AS3.
How to have a global try catch block??

hesslei
September 1st, 2008, 07:21 AM
Object-oriented programming (OOP) is something that is usually considered a black art for hardcore programmers, not a topic of conversation for Flash developers. However, when adobe introduced actionscript 3.0 to the mix, it changed everything. actionscript 3.0 is much more powerful than previous versions, allowing Flash developers to produce robust object-oriented applications. but with that power comes great responsibility—OOP is now a requirement, rather than optional, and there are new things to learn.


============
hesslei..



generated media (http://www.drivenwide.com)

keox
September 13th, 2008, 06:55 PM
Some easy example about actionscript and xml (http://flash-badass.blogspot.com/2008/09/easy-loading-xml-with-as30.html)

fld.pl
September 17th, 2008, 05:23 PM
ever had a problem with textfields using multiple font variants (normal, bold, italic)?
not anymore! ;-)

http://slorpy.pl/#post_1

kondapally
September 18th, 2008, 09:56 AM
The ActionScript virtual machine that runs ActionScript 3 code (AVM2) is completely different from the ActionScript virtual machin that runs ActionScript 1 and ActionScript 2 code (AVM1). Because of this, you cannot call commands in an AVM1 movie from and AVM2 movie or vise versa. The virtual machines just are not compatible in that respect and mostly run in their own kind of shell that allows it to only interact with code being played back in that same virtual machine. What that boils down to is that ActionScript 3 cannot talk to AS1 or AS2 - at least not directly.

One thing these two virtual machines have in common is their implementation of LocalConnection. Both virtual machines deal with local connections in essentially the same way - enough that local connections in AVM1 can receive events from AVM2 and vise versa. So should you come into a situation where you would need a movie published in ActionScript 3 to communicate with a movie published in ActionScript 1 or 2, using local connection is the way to go.


LocalConnection AS2 (http://livedocs.macromedia.com/flash/8/main/00002338.html)
LocalConnection AS3 (flash.net.LocalConnection) (http://livedocs.macromedia.com/flex/2/langref/flash/net/LocalConnection.html)
Example:

ActionScript Code:

// ActionScript 2 file, AS2animation.fla</p>
<p>// one movie clip animation named animation_mc on the timeline</p>
<p>&nbsp;</p>
<p>// local connection instance to receive events</p>
<p>var AVM_lc:LocalConnection = new LocalConnection();</p>
<p>&nbsp;</p>
<p>// stopAnimation event handler</p>
<p>AVM_lc.stopAnimation = function(){</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;animation_mc.stop();</p>
<p>}</p>
<p>&nbsp;</p>
<p>// listen for events for "AVM2toAVM1"</p>
<p>AVM_lc.connect("AVM2toAVM1");




ActionScript Code:

// ActionScript 3 file, AS3Loader.fla</p>
<p>&nbsp;</p>
<p>// local connection instance to communicate to AVM1 movie</p>
<p>var AVM_lc:LocalConnection = new LocalConnection();</p>
<p>&nbsp;</p>
<p>// loader loads AVM1 movie</p>
<p>var loader:Loader = new Loader();</p>
<p>loader.load(new URLRequest("AS2animation.swf"));</p>
<p>addChild(loader);</p>
<p>&nbsp;</p>
<p>// when AVM1 movie is clicked, call stopPlayback</p>
<p>loader.addEventListener(MouseEvent.CLICK, stopPlayback);</p>
<p>&nbsp;</p>
<p>function stopPlayback(event:MouseEvent):void {</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;// send stopAnimation event to "AVM2toAVM1" connection</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;AVM_lc.send("AVM2toAVM1", "stopAnimation");</p>
<p>}




The AS3 movie loads the AS2 movie into a Loader instance and places it on the screen. As it plays, the user can click the animation which calls stopPlayback sending the "stopAnimation" event to the local connection named "AVM2toAVM1". The AS2 movie is then able to receive that event in its stopAnimation event handler and tell the animation_mc clip to stop.


Hi,
I have used above code and it worked fine but with an error message
Error #2044: Unhandled StatusEvent:. level=error, code=

could you please tell me what is that error and what should I do to avoid it?

gavargas22
September 25th, 2008, 04:08 PM
When loading external movies or other display content (like images) into the Flash Player with ActionScript 3, you load the content into a Loader (http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/display/Loader.html) instance. Loaders provide containers for the external content to exist. No longer can you load external content into any movie clip, nor can you load SWFs into another level as levels no longer exist in ActionScript 3; you have to use a Loader instance.

You create Loader instances just like you create any other display object and add it to a display list using addChild(). To load content into the Loader you use Loader.load() passing in a URLRequest object containing the url of your content.

All DisplayObject instances have a loaderInfo property consisting of a LoaderInfo instance that provides information about that object's loaded content (if applicable). The Loader instance contains this property along with an additional contentLoaderInfo property which represents the LoaderInfo instance of the content being loaded. When loading content into a Loader, the contentLoaderInfo property is the object you would want to add listeners to for information about the loaded content such as when new bytes are being loaded into the player (for a preloader) and when loading has completed.

The events associated with LoaderInfo instances includes:
complete:Event — Dispatched by the associated LoaderInfo object when the file has completed loading. The complete event is always dispatched after the init event.
httpStatus:HTTPStatusEvent — Dispatched by the associated LoaderInfo object when a network request is made over HTTP and Flash Player can detect the HTTP status code.
init:Event — Dispatched by the associated LoaderInfo object when the properties and methods of the loaded SWF file are accessible. The init event always precedes the complete event.
ioError:IOErrorEvent — Dispatched by the associated LoaderInfo object when an input or output error occurs that causes a load operation to fail.
open:Event — Dispatched by the associated LoaderInfo object when the loading operation starts.
progress:ProgressEvent — Dispatched by the associated LoaderInfo object as data is received while load operation progresses.
unload:Event — Dispatched by the associated LoaderInfo object when a loaded object is removed.

Simple implementation:

var request:URLRequest = new URLRequest("content.swf");
var loader:Loader = new Loader();
loader.load(request);
addChild(loader);
The above example will blindly load content.swf within the loader instance. When/if the content has been successfully loaded, it will be displayed within the Loader instance which, since it has been added to the display list will be visible on the screen.

Loading with Error checking:

var request:URLRequest = new URLRequest("content.swf");
var loader:Loader = new Loader();

loader.contentLoaderInfo.addEventListener(IOErrorE vent.IO_ERROR, ioError);
function ioError(event:IOErrorEvent):void {
trace(event);
}

try {
loader.load(request);
}catch (error:SecurityError) {
trace(error);
}

addChild(loader);
Here error checking is applied to determine if there were any errors with the loading process. The first check is the ioError listener associated with the contentLoaderInfo property of the Loader instance catching any input or output errors assocated with the content being loaded. Note that the listener was added to contentLoaderInfo and not the loader itself.

The second check is the try-catch block used with the load() operation. The load method of Loader will throw SecurityError errors if:
The value of LoaderContext.securityDomain must be either null or SecurityDomain.currentDomain. This reflects the fact that you can only place the loaded media in its natural security sandbox or your own (the latter requires a policy file).
Local SWF files may not set LoaderContext.securityDomain to anything other than null. It is not permitted to import non-local media into a local sandbox, or to place other local media in anything other than its natural sandbox.
If the applicationDomain or securityDomain properties of the context parameter are from a disallowed domain.
If a local SWF file is attempting to use the securityDomain property of the context parameter.

It is recommended that you always check for errors, especially synchronous (thrown) errors since whenever an error is thrown, the current script block is exited leaving the remaining script unexecuted. Also, if the viewer is playing the movie in the debug version of the Flash Player, uncaught exceptions, both thrown and asynchronous errors (those handled by listeners) will appear in a pop-up dialog.

Loading with Preloader:

var request:URLRequest = new URLRequest("content.swf");
var loader:Loader = new Loader();

loader.contentLoaderInfo.addEventListener(Progress Event.PROGRESS, loadProgress);
loader.contentLoaderInfo.addEventListener(Event.CO MPLETE, loadComplete);

function loadProgress(event:ProgressEvent):void {
var percentLoaded:Number = event.bytesLoaded/event.bytesTotal;
percentLoaded = Math.round(percentLoaded * 100);
trace("Loading: "+percentLoaded+"%");
}
function loadComplete(event:Event):void {
trace("Complete");
}

loader.load(request);
addChild(loader);
Again, here, the contentLoaderInfo property is used to attach listeners. For preloading the PROGRESS event is used to obtain information about the loading progress. When completed, the COMPLETE event is dispatched. Traces are used in this example but an alternate preloader animation or visual can be adjusted within the PROGRESS event handler to visiually indicate the progression of the download.

Error checking was omitted from the above example for clarity but should always be used.

Hello, this is just an amazing tutorial thank you very much! I was just wondering how do I put it below the things that I already have in my stage, because it apparently automatically adds the movie clip to the top of the stage how do I send it back do you know?

emolen
October 3rd, 2008, 05:57 PM
look up setChildIndex, or you can also swap the childIndex if you know the depth of the child you are trying to swap with

geriactor
October 9th, 2008, 09:41 AM
The URLLoader class (flash.net.URLLoader (http://livedocs.adobe.com/flex/201/langref/flash/net/URLLoader.html)) in ActionScript 3 is used to load content from an external text file. When an external file has been loaded, its contents are stored within the data property of the URLLoader instance. Normally, the contents of a file, no matter what the file is, is loaded in as raw text. If you want the contents of a file to be loaded as variables (i.e. the loaded file is a text file whose contents consist of URL-encoded variables) then you will want to change the dataFormat property of the URLLoader.

The dataFormat property determines the format of the data being loaded into the URLLoader. Values for dataFormat are contained within the URLLoaderDataFormat class (flash.net.URLLoaderDataFormat (http://livedocs.adobe.com/flex/201/langref/flash/net/URLLoaderDataFormat.html)). Possible values include:

BINARY - Specifies that downloaded data is received as raw binary data.
TEXT - Specifies that downloaded data is received as text.
VARIABLES - Specifies that downloaded data is received as URL-encoded variables.

Using URLLoaderDataFormat.VARIABLES for the URLLoader's dataFormat, the loaded data will come in as a collection of variables instead of a string. The value of the data property will then be a URLVariables class (flash.net.URLVariables (http://livedocs.adobe.com/flex/201/langref/flash/net/URLVariables.html)) instance whose properties consist of the variables loaded.

ActionScript Code:

var loader:URLLoader = new URLLoader();

// specify format as being variables
loader.dataFormat = URLLoaderDataFormat.VARIABLES;

loader.addEventListener(Event.COMPLETE, varsLoaded);

// vars.txt contents: foo=bar&foo2=bar2
loader.load(new URLRequest("vars.txt"));

function varsLoaded (event:Event):void {
&nbsp;&nbsp;&nbsp;&nbsp;trace(loader.data is URLVariables); // true
&nbsp;&nbsp;&nbsp;&nbsp;trace(loader.data.foo); // bar
&nbsp;&nbsp;&nbsp;&nbsp;trace(loader.data.foo2); // bar2
}



My AS3 code generates a random number which is used in a switch statement to select one of 10 .flv files for streaming. The upper limit used in the Math.ceil() method is stored in vars.txt as the name value pair: totalVideos=10.

My problem is about how to access the urlVars.totalVideos variable from outside of the onComplete function (see code).

Within the function I can trace the variable and assign it to a global variable, but once outside of the function, that global variable still equals 0.

Perhaps the variable can be accessed by somehow configuring the onComplete function to return the variable? What is the right way to go about this?


var videoTotal:Number = 0;
// Get random number's upper limit from vars.txt, content: totalVideos=10
var vidTotal:URLLoader = new URLLoader();
vidTotal.dataFormat = URLLoaderDataFormat.VARIABLES;
vidTotal.addEventListener(Event.COMPLETE, onComplete, false, 0 , true);
vidTotal.load(new URLRequest("vars.txt"));

function onComplete(evt:Event):void {

var urlVars:URLVariables = evt.target.data;
videoTotal = Number(urlVars.totalVideos); // videoTotal = 10
}

trace(" videoTotal = " + videoTotal); // displays videoTotal = 0

// Generate a random number with videoTotal as upper limit
var n:Number = Math.ceil(videoTotal*Math.random());
trace("n is: " + 0); // n is: 0

randygland2
October 9th, 2008, 12:18 PM
Can I use this duplicate Movie as3 class with Bitmap or BitmapData objects? or only MovieClips? I tried casting my Bitmap as a Movie but had no luck :(

randygland2
October 9th, 2008, 12:23 PM
Can I use this duplicate Movie as3 class with Bitmap or BitmapData objects? or only MovieClips? I tried casting my Bitmap as a Movie but had no luck :(
]
nervermind.. all i had to do was this:

var newInstance:Bitmap = new Bitmap(bitmapData);
addChild(newInstance);
newInstance.x = 200;

great class tho.. x

geriactor
October 9th, 2008, 03:01 PM
I see now that initiating the rest of the program from within onComplete, using function calls, will allow those calls to fall within the scope of URLLoaderDataFormat.VARIABLES.

import fl.video.FLVPlayback;
var videoNumber:Number = 0;
var videoName:String = "";
// Get number of videos available from vars.txt
var getTotal:URLLoader = new URLLoader();
getTotal.dataFormat = URLLoaderDataFormat.VARIABLES;
getTotal.addEventListener(Event.COMPLETE, onComplete, false, 0 , true);
getTotal.load(new URLRequest("vars.txt"));

function onComplete(evt:Event):void {
var urlVars:URLVariables = evt.target.data;
videoNumber = getRanNo(urlVars.totalVideos);
videoName = chooseVideo(videoNumber);
playVideo(videoName);
}

cjt3007
October 15th, 2008, 06:01 AM
So, if I had a main flash file that loads an external flash file, how do I access other movie clips in the main flash file from the external flash file?

In as2 all I had to do was type
root.SomeMovie.gotAndPlay("External Loaded");
in the external files actionscirpt

but this doesn't work in as3...

PLEASE HELP!!!

essentially what I am trying to do is disable _lockroot I guess

Zontaluma
October 16th, 2008, 03:03 AM
Senocular--

I've had a few unsuccessful jumps from AS2 to AS3. Being an artist, the need for visually laying things out on the stage...canvas ;) is a necessity. I've really been having problems doing this with code. I didn't think I'd ever graps the new concept of managing depths, but after reading your quick, easy to understand and to the point post, I'm off and running!!! I feel that I've made a significant step forward. I'm going to add your tips to my daily mind enhancing activities.

Thanks!

~Z


Because of how the display list works with ActionScript 3, some methods of depth sorting will no longer work. One in particular is sorting objects on the screen based on their y location. In ActionScript 1 and 2, you could simply tell the clip to swapDepths at its _y location and be done with it. With AS3, this is no longer possible since no gaps can exist within the depths display list ("array").

An approach to obtaining the same functionality in AS3 is possible through an sorted array. Store the objects you want to arrange in an array. Then sort that array based on the y properties of the display objects within. All you have to do after that is place them in the display list in the order sorted. Ex:
ActionScript Code:

var sortedItems:Array = new Array(mc1, mc2, mc3);
function arrange():void {
&nbsp;&nbsp;&nbsp;&nbsp;sortedItems.sortOn("y", Array.NUMERIC);
&nbsp;&nbsp;&nbsp;&nbsp;var i:int = sortedItems.length;
&nbsp;&nbsp;&nbsp;&nbsp;while(i--){
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;if (getChildAt(i) != sortedItems[i]) {
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;setChildIndex(sortedItems[i], i);
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}
&nbsp;&nbsp;&nbsp;&nbsp;}
}



Here the sortedItems array stores the display objects being sorted (mc1 - mc3). In the arrange function, that array is sorted based on their y properties and then added to the display list at their locations within the array (if not already there).

Though this is not quite as easy as swaping to the depth of the _y property, it still proves a fairly efficient means of sorting objects on the screen based on their y location.

jochemvermeiren
October 22nd, 2008, 10:05 AM
I've tried to work it out, but my communication between AS3 and as2 won't work. Somebody any idees?

AS3 code:

var outgoingLocal:LocalConnection = new LocalConnection();
outgoingLocal.send("vidplayer","methodToExecute","videolink");


AS2 code:

var incoming_lc:LocalConnection = new LocalConnection();
incoming_lc.connect("vidplayer");
incoming_lc.methodToExecute = function(param:String):Void {
txtField.text= param;
};

can someone help me?

backwater
October 26th, 2008, 11:56 AM
I know that thanks to Senocular have already been given, but I have to offer my own
thanks to his swap depth solution in AS3. It seems to be one of the few examples where
AS2 offers simpler solutions than AS3. (at least in my opinion)

I was trying to write an image carousel in AS3 and Senoc's sorted array solution saved my bacon. I'm also inspired to learn more about sorted arrays.

Dan

AlePereira
October 27th, 2008, 11:15 AM
How a could send a variable or other action from "content.swf" to root or others loading files?

HotN
November 2nd, 2008, 08:28 PM
As with AS2, you can also use the wildcard character (*) in AS3 to import all classes within a package.Does this mean that all classes are imported or does it simply import the classes that are actually implemented from the package?
Basically, is there an advantage to importing specific classes instead of just using the wildcard?

McGuffin
November 2nd, 2008, 09:31 PM
Does this mean that all classes are imported or does it simply import the classes that are actually implemented from the package?
Basically, is there an advantage to importing specific classes instead of just using the wildcard?

When Flash is compiling your SWF, it will only include those that are actually used, rather than just imported. I still type out class names I'm importing instead of using the wildcard *, because I like to know exactly what classes are being used, but otherwise there is no reason to not use the wildcard, as far as I know.

Loose Seal
November 8th, 2008, 05:18 AM
Can somebody please talk me through some coding I'm doing involving adding sound. I'm a complete noob and I'm panicking here.

ididnteatanycorn@hotmail.com. Any help would be welcome.

bmarrant
November 13th, 2008, 02:12 PM
ActionScript 3 no longer has a duplicateMovieClip method for MovieClip instances (or any DisplayObject instances). Instead, it's suggested that you just create a new instance of the display object you wish to duplicate using its constructor. This, however, is not the same as duplicateMovieClip, and, really, is more like using AS1 and AS2's attachMovieClip. For a more accurate representation of duplicateMovieClip in AS3, consider the following function:

package com.senocular.display {

import flash.display.DisplayObject;
import flash.geom.Rectangle;

/**
* duplicateDisplayObject
* creates a duplicate of the DisplayObject passed.
* similar to duplicateMovieClip in AVM1
* @param target the display object to duplicate
* @param autoAdd if true, adds the duplicate to the display list
* in which target was located
* @return a duplicate instance of target
*/
public function duplicateDisplayObject(target:DisplayObject, autoAdd:Boolean = false):DisplayObject {
// create duplicate
var targetClass:Class = Object(target).constructor;
var duplicate:DisplayObject = new targetClass();

// duplicate properties
duplicate.transform = target.transform;
duplicate.filters = target.filters;
duplicate.cacheAsBitmap = target.cacheAsBitmap;
duplicate.opaqueBackground = target.opaqueBackground;
if (target.scale9Grid) {
var rect:Rectangle = target.scale9Grid;
// WAS Flash 9 bug where returned scale9Grid is 20x larger than assigned
// rect.x /= 20, rect.y /= 20, rect.width /= 20, rect.height /= 20;
duplicate.scale9Grid = rect;
}

// add to target parent's display list
// if autoAdd was provided as true
if (autoAdd && target.parent) {
target.parent.addChild(duplicate);
}
return duplicate;
}
}
As you can see, this function (duplicateDisplayObject) takes care of making sure a duplicated instance also retains all the information retained by duplicateMovieClip such as transformation, filters, chaching as bitmap, etc.

Note: There is currently a bug in Flash Player 9 that causes incorrect values to be returned from the scale9Grid property of display objects. This function compensates for that but may need to be edited should this bug be fixed.

Usage:

import com.senocular.display.duplicateDisplayObject;

// create duplicate and assign to newInstance variable
// using true for autoAdd automatically adds the newInstance
// into the display list where myOldSprite is located
var newInstance:Sprite = duplicateDisplayObject(myOldSprite, true);
newInstance.x += 100; // shift to see duplicate

The only thing duplicateMovieClip does that this does not is copy dynamic drawing information. Currently, the graphics object in display objects cannot be duplicated so there is no way to obtain that information for duplicates in duplicateDisplayObject.
This method doesn't seem to copy the MovieClips frame scripts. Is this something you've run into?

sgtPeper
November 21st, 2008, 12:49 PM
Debbugin for Dummies:

Debuggin-101
Hi Senocular, great tips. Look, i´m a designer and all this programming things are kind of confuse for me. I must confese that i miss the old days when you could make a great flash sites with the comunity´s code. Now is not that simple.

So, I got this error:

TypeError: Error #1010: A Term it is not defined and has no properties at lookandFeel3_fla::MainTimeline/frame3()

The thing is that I have no frame3, what is that? Where I can look at? What can I do or how?
I have classes, objects in the stage, so do you recommened to make a check list instances names, go to the classes? Why frame 3 in a 1 frame movie? What movie clip could cause this error? But the must important, how can I debug? Do you have a technique?

I tried to run your code at the end of my movie, to debug but I don´t know what to change. For example, objectReference refers to a MC like box_mc? Then I´ll check with others MCs? And for code, what code goes there?

if (box_mc && box_mc.property) {
// code
// what code I should use???
}

This is the link:
http://www.rayacosta.com/clientes/sector/index2.php

Thanks.

nilanjan
November 25th, 2008, 07:55 AM
Each Bitmap instance in ActionScript 3 references a separate BitmapData instance as a source for its graphics data. When you have two Bitmap instances, you potentially have 2 separate BitmapData instances as well.

If you want to have two Bitmaps that look exactly the same, you can save memory by making both of those bitmaps reference the same BitmapData instance through ActionScript. All you need to do is create the second Bitmap using the BitmapData from the original. Any changes made to the BitmapData instance will affect both Bitmaps on screen.


ActionScript Code:

// copyBitmap will appear as a copy of </p>
<p>// the originalBitmap Bitmap instance</p>
<p>var copyBitmap:Bitmap = new Bitmap(originalBitmap.bitmapData);




Hi,

Shouldn't a same BitmapData object applied to two different Bitmap objects save memory? Or applying with reference to the bitmapData property of the other one is the catch?

Regards
Nilanjan

Tim John
December 2nd, 2008, 12:10 PM
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.

Hey Senocular,
You mentioned that filters are not taken into account using these methods - is there any way to get the actual size of a display object including its filters?

tester123
December 4th, 2008, 12:03 PM
how would one include that validation of emails that are in the fallowing form firstname.lastname@something.com Thanks!![/quote]

nitzuga
December 9th, 2008, 12:17 PM
if you have to movie clips, wich are mcParent, and mcSon, mcParent is the parent of mcSon.

So if you are in the mcSon timeline, and want to tell something to mcSon, like going to a differente frame or anything you want, try something like
var myMcParent:MovieClip = MovieClip(this.parent);
myMcParent.gotoAndPlay("somewhere");

in that way you should have a reference of your parent, allowing you to work with it

felipebroliveir
January 6th, 2009, 11:30 AM
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 (http://livedocs.macromedia.com/flex/2/langref/flash/media/SoundMixer.html)). It's computeSpectrum method (static) places sound spectrum information in a ByteArray instance which can then be used to generate a visualization.
ActionScript Code:

// play sound...
var spectrumInfo:ByteArray = new ByteArray();
SoundMixer.computeSpectrum(spectrumInfo);
// spectrumInfo is now a byte array with sound spectrum info





AS3 don't have a class SoundMixer and method computeSpectrum for microphones, anyone know how to use this method with microphones or sounds playing live?

Dr.Lee
January 16th, 2009, 03:55 PM
Yes indeed Action Script3.0 is really amazing script.I used it on several of my websites without any problem.
And yeah I found the language easy enough to understand. Simulation pret immobilier (http://simulationpretimmobilier.net)

Very good script for sure!

gyurxi551
February 6th, 2009, 04:51 AM
The new int data type in ActionScript 3.0 is a new type for Number.
Most of this speed, however, is limited to bitwise operations. Normal mathematical operations can actually be slower for ints. The reason for this is that ECMAScript (ActionScript) needs to calculate those operations as Number no matter what the data type of your original value. What this means is that if you multiply two ints together, Flash will need to internally cast or convert those values to Number and then perform the operation. For these basic mathematical operations, Number can actually be faster than int. Depending on how you work with your numbers, if you're looking for speed, you may need to type appropriately. [...]



Thank you. But I found an intresting article about it:
http://kuwamoto.org/2006/06/15/avoid-ints-in-actionscript/
test results:
http://www.gskinner.com/blog/archives/2006/06/types_in_as3_in.html

Sorry, now I see there is also a topic about it:
http://www.actionscript.org/forums/showthread.php3?t=1123 (http://www.actionscript.org/forums/showthread.php3?t=112352)52

Gyurci

aneuryzma
February 22nd, 2009, 03:44 AM
Hi, thanks for the depth sorting code. By the way I get an error because postedItems is not child of my movieclip, so I can't get or set childIndex.

Where am I wrong ?

thegreensurfer
March 16th, 2009, 05:06 PM
You can pass variables to SWF files in the object/embed code used to display a SWF in HTML. You can do this two ways, one using URL variables (query string) at the end of the SWF path, or through the FlashVars property.

<!-- URL Variables -->
<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0" width="640" height="500" align="middle">
<param name="allowScriptAccess" value="sameDomain" />
<param name="movie" value="flashMovie.swf?myVar=1" />
<param name="quality" value="high" />
<param name="bgcolor" value="#EFF7F6" />
<embed src="flashMovie.swf?myVar=1" quality="high" bgcolor="#EFF7F6" width="640" height="500" align="middle" allowScriptAccess="sameDomain" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" />
</object>
<!-- FlashVars -->
<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0" width="550" height="400" align="middle">
<param name="allowScriptAccess" value="sameDomain" />
<param name="movie" value="flashMovie.swf" />
<param name="quality" value="high" />
<param name="bgcolor" value="#FFFFFF" />
<param name="FlashVars" value="myVar=1" />
<embed src="flashMovie.swf" FlashVars="myVar=1" quality="high" bgcolor="#FFFFFF" width="550" height="400" align="middle" allowScriptAccess="sameDomain" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" />
</object>In ActionScript 2, these variables were simply defined as variables in _root. This has changed for ActionScript 3. Now these variables are accessible in a parameters object located in the root loaderInfo object.

Given the HTML embed code above, you would access the myVar property using:
ActionScript Code:

root.loaderInfo.parameters.myVar;




I need to dynamically pass falshvars to a flash application and I am using the code below in an aspx page, however it does not work can anyone help?


<script type="text/javascript" language="javascript">
if (AC_FL_RunContent == 0)
{
alert("This page requires AC_RunActiveContent.js.");
}
else
{
//begin AC code
AC_FL_RunContent
(
'codebase', 'http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0',
'width', '500',
'height', '450',
'src', 'Chat',
'quality', 'high',
'pluginspage', 'http://www.macromedia.com/go/getflashplayer',
'align', 'middle',
'play', 'true',
'loop', 'true',
'scale', 'showall',
'wmode', 'window',
'devicefont', 'false',
'id', 'Chat',
'bgcolor', '#ffffff',
'name', 'Chat',
'menu', 'true',
'allowFullScreen', 'false',
'allowScriptAccess','sameDomain',
'movie', 'Chat',
'FlashVars', 'userName=getCookie(userName)&instance=getCookie(i nstance)',
'salign', ''
);
//end AC code
}
</script>
<noscript>
<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0" width="500" height="450" id="Chat" align="middle">
<param name="allowScriptAccess" value="sameDomain" />
<param name="allowFullScreen" value="false" />
<param name="movie" value="Chat.swf" />
<param name="quality" value="high" />
<param name="bgcolor" value="#ffffff" />
<param name="FlashVars" value="userName==<%=Request.Cookies["userName"]%>&instance=<%=Request.Cookies["instance"]%>" />
<embed src="Chat.swf" FlashVars="userName=<%=Request.Cookies["userName"]%>&instance=<%=Request.Cookies["instance"]%>" quality="high" bgcolor="#ffffff" width="500" height="450"
name="Chat" align="middle" allowScriptAccess="sameDomain" allowFullScreen="false" type="application/x-shockwave-flash"
pluginspage="http://www.macromedia.com/go/getflashplayer" />
</object>
</noscript>
<script type="text/javascript" language="javascript">
<!--
// a simple function that returns the value of a cookie
function getCookie(name)
{
if (document.cookie)
{
var cookies=document.cookie.split(";");
for (var i=0; i<cookies.length; i++)
{
var varName=(cookies[i].split("=")[0]);
var varValue=(cookies[i].split("=")[1]);

// the next 2 lines trim whitespaces (Netscape 7 problem)
while (varName.charAt(0)==" ")
varName=varName.substr(1,varName.length);
if (varName==name)
return escape(varValue);
}
}
}
//-->
</script>

Galbatorix
March 20th, 2009, 09:56 PM
I am building a flash game as a school/personal project. I want to increase the frame rate from 12 to 120 due to the fact that something can only go so fast before the length of, in this case, this missile is not long enough to cover all of the space between one frame and the next. This affects the hits tests for exploding said missile because it might not hit the desired object. But if I increase the frame rate, I would have to make every single animation 10 times longer to get the same running time of the animation. Is there any way to automatically increase the number of frames, or am i doomed to having to extend the animations by hand?

Thanks in advance,
Galb

Krilnon
March 20th, 2009, 10:02 PM
There are different approaches to hit testing that you could use to avoid having to adjust the frame rate

Galbatorix
March 21st, 2009, 10:13 AM
I'm not worried about the hit tests, just about everything moving 10 times faster than normal. To get the same length in seconds for each animation, I would have to make a 10 frame animation 100 frames, 60 frame animation 600 frames, etc. Was just wondering if there's a shortcut to this or something I could do in AS3.

EDIT: What would those methods be?

Gnoll
March 21st, 2009, 06:15 PM
@Galbatrox

You could check distance between your 2 objects before you move and if it is close enough to your speed then explode() or whatever :)

Also if it is running at 100 frames per second (I wouldn't suggest greater than 30 for the sake of people with bad computers) It will be hittesting 100 times per second so the same chance of the hitting, (assuming you are hittesting on enterframe.

Overall I would say just increasing the speed of your missile and calculating distance should increase the overall performance and be much neater.

Good luck, Gnoll

Galbatorix
March 24th, 2009, 06:35 PM
@Galbatorix

You could check distance between your 2 objects before you move and if it is close enough to your speed then explode() or whatever :)

Also if it is running at 100 frames per second (I wouldn't suggest greater than 30 for the sake of people with bad computers) It will be hittesting 100 times per second so the same chance of the hitting, (assuming you are hittesting on enterframe.

Overall I would say just increasing the speed of your missile and calculating distance should increase the overall performance and be much neater.

Good luck, Gnoll

Thanks! I'll try that. I also have another question. What class would an instance name be? for example:

if(missile3.ready==true){
i="3";
}

I do this because I have one huge function that manages the firing of the missile. I have

var missile="missile"+i;

So that returns "missile3". is there a way to then refer to that as an instance name?
As in,

missile.gotoAndPlay(2);

and have it go into missile3 and play frame 2?
No I don't have any symbols named "missile" on my stage. I've tried multiple methods, none have worked. any ideas?

Gnoll
March 24th, 2009, 07:21 PM
Well var missile="missile"+i; will give you a string, if you want to get a MovieClip do var missile=getChildByName("missile"+i), assuming you gave it the name "missile3" when you created it. I would have the function require the movieclip eg. function shoot(missile:MovieClip) { } then just use missile from there.

Good luck,
Gnoll

Galbatorix
March 24th, 2009, 07:40 PM
missile3 is just an instance name. I have 10 missile symbols (Symbol name is missileShot), but with instance names of missile1-missile10. I had this working with just one missile but am trying to fire more than one at once.

Gnoll
March 24th, 2009, 07:45 PM
Ok just use the getChildByName() although I would suggest passing them to a function

themuffinman
March 27th, 2009, 11:38 PM
When loading external movies or other display content (like images) into the Flash Player with ActionScript 3, you load the content into a Loader (http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/display/Loader.html) instance. Loaders provide containers for the external content to exist. No longer can you load external content into any movie clip, nor can you load SWFs into another level as levels no longer exist in ActionScript 3; you have to use a Loader instance.

You create Loader instances just like you create any other display object and add it to a display list using addChild(). To load content into the Loader you use Loader.load() passing in a URLRequest object containing the url of your content.

All DisplayObject instances have a loaderInfo property consisting of a LoaderInfo instance that provides information about that object's loaded content (if applicable). The Loader instance contains this property along with an additional contentLoaderInfo property which represents the LoaderInfo instance of the content being loaded. When loading content into a Loader, the contentLoaderInfo property is the object you would want to add listeners to for information about the loaded content such as when new bytes are being loaded into the player (for a preloader) and when loading has completed.

The events associated with LoaderInfo instances includes:

complete:Event — Dispatched by the associated LoaderInfo object when the file has completed loading. The complete event is always dispatched after the init event.
httpStatus:HTTPStatusEvent — Dispatched by the associated LoaderInfo object when a network request is made over HTTP and Flash Player can detect the HTTP status code.
init:Event — Dispatched by the associated LoaderInfo object when the properties and methods of the loaded SWF file are accessible. The init event always precedes the complete event.
ioError:IOErrorEvent — Dispatched by the associated LoaderInfo object when an input or output error occurs that causes a load operation to fail.
open:Event — Dispatched by the associated LoaderInfo object when the loading operation starts.
progress:ProgressEvent — Dispatched by the associated LoaderInfo object as data is received while load operation progresses.
unload:Event — Dispatched by the associated LoaderInfo object when a loaded object is removed.


Simple implementation:
ActionScript Code:

var request:URLRequest = new URLRequest("content.swf");
var loader:Loader = new Loader();
loader.load(request);
addChild(loader);



The above example will blindly load content.swf within the loader instance. When/if the content has been successfully loaded, it will be displayed within the Loader instance which, since it has been added to the display list will be visible on the screen.

Loading with Error checking:
ActionScript Code:

var request:URLRequest = new URLRequest("content.swf");
var loader:Loader = new Loader();

loader.contentLoaderInfo.addEventListener(IOErrorE vent.IO_ERROR, ioError);
function ioError(event:IOErrorEvent):void {
&nbsp;&nbsp;&nbsp;&nbsp;trace(event);
}

try {
&nbsp;&nbsp;&nbsp;&nbsp;loader.load(request);
}catch (error:SecurityError) {
&nbsp;&nbsp;&nbsp;&nbsp;trace(error);
}

addChild(loader);



Here error checking is applied to determine if there were any errors with the loading process. The first check is the ioError listener associated with the contentLoaderInfo property of the Loader instance catching any input or output errors assocated with the content being loaded. Note that the listener was added to contentLoaderInfo and not the loader itself.

The second check is the try-catch block used with the load() operation. The load method of Loader will throw SecurityError errors if:

The value of LoaderContext.securityDomain must be either null or SecurityDomain.currentDomain. This reflects the fact that you can only place the loaded media in its natural security sandbox or your own (the latter requires a policy file).
Local SWF files may not set LoaderContext.securityDomain to anything other than null. It is not permitted to import non-local media into a local sandbox, or to place other local media in anything other than its natural sandbox.
If the applicationDomain or securityDomain properties of the context parameter are from a disallowed domain.
If a local SWF file is attempting to use the securityDomain property of the context parameter.


It is recommended that you always check for errors, especially synchronous (thrown) errors since whenever an error is thrown, the current script block is exited leaving the remaining script unexecuted. Also, if the viewer is playing the movie in the debug version of the Flash Player, uncaught exceptions, both thrown and asynchronous errors (those handled by listeners) will appear in a pop-up dialog.

Loading with Preloader:
ActionScript Code:

var request:URLRequest = new URLRequest("content.swf");
var loader:Loader = new Loader();

loader.contentLoaderInfo.addEventListener(Progress Event.PROGRESS, loadProgress);
loader.contentLoaderInfo.addEventListener(Event.CO MPLETE, loadComplete);

function loadProgress(event:ProgressEvent):void {
&nbsp;&nbsp;&nbsp;&nbsp;var percentLoaded:Number = event.bytesLoaded/event.bytesTotal;
&nbsp;&nbsp;&nbsp;&nbsp;percentLoaded = Math.round(percentLoaded * 100);
&nbsp;&nbsp;&nbsp;&nbsp;trace("Loading: "+percentLoaded+"%");
}
function loadComplete(event:Event):void {
&nbsp;&nbsp;&nbsp;&nbsp;trace("Complete");
}

loader.load(request);
addChild(loader);



Again, here, the contentLoaderInfo property is used to attach listeners. For preloading the PROGRESS event is used to obtain information about the loading progress. When completed, the COMPLETE event is dispatched. Traces are used in this example but an alternate preloader animation or visual can be adjusted within the PROGRESS event handler to visiually indicate the progression of the download.

Error checking was omitted from the above example for clarity but should always be used.

How do we send varaibles/data to the loaded .swf files?

SuperGoove
April 2nd, 2009, 06:16 AM
Just FYI


Here's an example of how one might validate email using ActionScript 3's Regular Expression class (Top level RegExp (http://livedocs.macromedia.com/flex/2/langref/RegExp.html)):

ActionScript Code:

function isValidEmail(email:String):Boolean {
&nbsp;&nbsp;&nbsp;&nbsp;var emailExpression:RegExp = /^[a-z][\w.-]+@\w[\w.-]+\.[\w.-]*[a-z][a-z]$/i;
&nbsp;&nbsp;&nbsp;&nbsp;return emailExpression.test(email);
}
//...
trace(isValidEmail("senocular@example.com")); // true
trace(isValidEmail("@example.com")); // false
trace(isValidEmail("senocular@example")); // false
trace(isValidEmail("seno\\cular@example.com")); // false

gyurxi551
April 22nd, 2009, 03:26 AM
Unlike ActionScript 1 and 2, there is no onReleaseOutside event [...]Once that happens, you can check the event.target to see if the mouseUp is happening for your original object (be sure to also check instances within it) or something else such as the stage or another display object.

Example:
ActionScript Code:

// create a circle to click
var circle:Sprite = new Sprite();
circle.graphics.beginFill(0x4080A0);
circle.graphics.drawCircle(50, 50, 25);
addChild(circle);

circle.addEventListener(MouseEvent.MOUSE_DOWN, mouseDown);
function mouseDown(event:MouseEvent):void {
// down, now check for global mouseUp
stage.addEventListener(MouseEvent.MOUSE_UP, mouseUp);
}
function mouseUp(event:MouseEvent):void {
if (event.target == circle || circle.contains(event.target)){
// mouse is up over circle (onRelease)
// (if circle is not a DisplayObjectContainer,
// you do not need to use the contains check)
}else{
// mouse is up outside circle (onReleaseOutside)
}

// be sure to clean up stage listener
stage.removeEventListener(MouseEvent.MOUSE_UP, mouseUp);
}




Thanks Senocular, but I have a little problem with this. I tried it, but error appears:
1118: Implicit coercion of a value with static type Object to a possibly unrelated type flash.display.DisplayObject.
The error comes from this line:
if (event.target == circle || circle.contains(event.target)){

I tried event.target.name ="circle" and
event.target == circle as MovieClip

and so on, but suddenly I cannot figure it out. :hat:
What did I wrong?
THX

HotN
April 22nd, 2009, 08:49 AM
The error comes from this line:
[/I]if (event.target == circle || circle.contains(event.target))[COLOR=#000000]{


The method contains() is looking for a DisplayObject as a parameter. Event.target is of the generic type Object, so it must be casted first.

Try:

if (event.target == circle || circle.contains(DisplayObject(event.target))){

gyurxi551
April 23rd, 2009, 04:41 AM
The method contains() is looking for a DisplayObject as a parameter. Event.target is of the generic type Object, so it must be casted first.

Try:

if (event.target == circle || circle.contains(DisplayObject(event.target))){

Thanks, I'll try it. :beer:

Thunder_one
April 29th, 2009, 06:23 PM
been battle this _global function for ages now and cant see to migrate my AS2 code to AS3.
what If I have a function call:

_global.ibm_get_Myname = function ()
{
//my code here//
}
Do I have to add this function into the Globals
package ?


package {
public class glo {
public static var bal:Object = new Object();
}

_global.ibm_get_Myname = function () {
//my code here//
}

}
I am a newbee..
Thanks

gyurxi551
April 30th, 2009, 03:13 AM
Hi,
To achieve this, I suggest you to create a Proxy folder for example, and make a GlobalClass there:


package Proxy
{
public class GlobalClass
{
public static function ibm_get_Myname() {
trace("OK.")
}

}
}Then in the document class or in any other class (I always use it, because from this there'll be no framescript :blah: ) just import it, and then use it:

package
{
import flash.display.Sprite
import Proxy.GlobalClass
/**
* ...
* @author Gyurci
*/
public class DocClass extends Sprite
{

public function DocClass()
{
GlobalClass.ibm_get_Myname(); }

}

}I used to do that, but for only to reach any mc in the fla file, whic is already on the stage. If you bulid tidy classes you will have no longer globals. =)

Thunder_one
April 30th, 2009, 03:36 PM
Thanks for replied me, and sharing your files.
Got it working in a small test project, nice job...

I am stuck with this _goblal.name function for this project, Is a old AS2 actionscript code.
and I am trying to migrate it to AS3

after this I'll make sure to drop it..

I assume the Proxy.GlobalClass can be call the same way if I' am on a button Right ?


private function myButtonClick(arg1:flash.events.MouseEvent):void
{
GlobalClass.ibm_get_Myname();
}

Thanks for your help here, Much appreciated

arnab
May 13th, 2009, 12:23 PM
Hello,

I keep reading your posts. I had read the post "How the Stage, root and timeline fit together " time and again to get a better understanding of the workings of the new display hierarchy.However its not been entirely clear to me. Could you kindly draw up a simple chart illustrating the lines in this posts as pictures in that chart mapping this hierarchy.Once this is visual it would help us understand better I feel.Just a request though.

For eg:
I have a simple piece of code which reads


package
{
import flash.display.DisplayObjectContainer;
import flash.display.Sprite;
import flash.text.TextField;

public class DisplayListExample extends Sprite
{
public function DisplayListExample()
{
//Create a display Object in Actionscript Engine
var hello:TextField=new TextField();
hello.text="hello";
//Create the display object in the rendering engine
//by adding it to the display list so that the textfield
//is drawn on the screen.
//trace(this);
//DisplayObjectContainer.addChild(hello);//error
DisplayObjectContainer(root).addChild(hello);
//trace(root==this);//true
//addChild(hello);
}
}///;

}//;

I fill in the Document Class as : DisplayListExample


DisplayObjectContainer.addChild(hello); this line will throw an error although

DisplayObjectContainer(root).addChild(hello); this line will not.This type of referencing

of the root is not very clear.

also

trace(this); would trace : [object DisplayListExample] which is fine.

but

trace(root==this); would yeild true

here "this" is the [object DisplayListExample] , now why would it be the same as "root".I think root is unique and one for every swf.

Thank you.

arnab
May 13th, 2009, 12:26 PM
Hello,

I keep reading your posts. I had read the post "How the Stage, root and timeline fit together " time and again to get a better understanding of the workings of the new display hierarchy.However its not been entirely clear to me. Could you kindly draw up a simple chart illustrating the lines in this posts as pictures in that chart mapping this hierarchy.Once this is visual it would help us understand better I feel.Just a request though.

For eg:
I have a simple piece of code which reads


package
{
import flash.display.DisplayObjectContainer;
import flash.display.Sprite;
import flash.text.TextField;

public class DisplayListExample extends Sprite
{
public function DisplayListExample()
{
//Create a display Object in Actionscript Engine
var hello:TextField=new TextField();
hello.text="hello";
//Create the display object in the rendering engine
//by adding it to the display list so that the textfield
//is drawn on the screen.
//trace(this);
//DisplayObjectContainer.addChild(hello);//error
DisplayObjectContainer(root).addChild(hello);
//trace(root==this);//true
//addChild(hello);
}
}///;

}//;

I fill in the Document Class as : DisplayListExample


DisplayObjectContainer.addChild(hello); this line will throw an error although

DisplayObjectContainer(root).addChild(hello); this line will not.This type of referencing

of the root is not very clear.

also

trace(this); would trace : [object DisplayListExample] which is fine.

but

trace(root==this); would yeild true

here "this" is the [object DisplayListExample] , now why would it be the same as "root".I think root is unique and one for every swf.

Thank you.

robmarston
May 18th, 2009, 04:29 PM
Would this method work for copying a display object? I'm attempting to clone a Sprite with series of Loader objects in it and it's not letting me add that child to the stage.

srivello
June 1st, 2009, 04:44 AM
Great post. I love the idea of assisting developers so they only seeing the methods via intellisense (of Flex Builder) for methods they need to see. I created a new demo to show that off. http://www.blog.rivello.org/?p=422

cancerinform
June 6th, 2009, 11:25 AM
This is very nice :)

Just for the sake of completeness, if the MovieClip contains other MovieClips they are usually not copied. Adding this loop will do that and position them at the correct place. Also I noticed setting target to DisplayObject gives errors sometimes. So setting it to Sprite even it is a Movieclip does the job.



package com.senocular.display
{
import flash.display.Sprite;
import flash.geom.Rectangle;
public function duplicateDisplayObject (target:Sprite, autoAdd:Boolean = false):Sprite
{
var targetClass:Class = Object(target).constructor;
var duplicate:Sprite = new targetClass();
duplicate.transform = target.transform;
duplicate.filters = target.filters;
duplicate.cacheAsBitmap = target.cacheAsBitmap;
duplicate.opaqueBackground = target.opaqueBackground;
if (target.scale9Grid)
{
var rect:Rectangle = target.scale9Grid;
duplicate.scale9Grid = rect;
}
/*
* This will duplicate also any MovieClips inside a MovieClip.
*/
for (var i:int = 0; i<target.numChildren; i++)
{
if (target.getChildAt(i).toString() != "[object Shape]")
{
var childClass:Class = Object(target.getChildAt(i)).constructor;
var child:Sprite = new childClass();
child.transform = target.getChildAt(i).transform;
child.filters = target.getChildAt(i).filters;
child.cacheAsBitmap = target.getChildAt(i).cacheAsBitmap;
child.opaqueBackground = target.getChildAt(i).opaqueBackground;
child.x = target.getChildAt(i).x;
child.y = target.getChildAt(i).y;
duplicate.addChild(child);
}
}
if (autoAdd && target.parent)
{
target.parent.addChild (duplicate);
}
return duplicate;
}
}

Fla example:

import com.senocular.display.duplicateDisplayObject;
var a:Clip = new Clip();
a.x = 200;
a.y = 200;
addChild (a);
var b:Clip2 = new Clip2();
b.x = 50;
b.y = 15;
a.addChild (b);
var newInstance:Sprite = duplicateDisplayObject(a,true);
newInstance.x = 0;

cancerinform
June 6th, 2009, 03:21 PM
So setting it to Sprite even it is a Movieclip does the job.

Of course if the target is a Movieclip the target datatype has to be a Movieclip.

Here is another addition. If you have a Loader object inside the Movieclip to be duplicated then all you need to do is add this statement inside of the for loop.



duplicate.addChild(child);
if(target.getChildAt(i).toString() == "[object Loader]")
{
var request:URLRequest = new URLRequest(Loader(target.getChildAt(i)).contentLoa derInfo.url);
Loader(child).load(request);
}

However, that works only when the object is loaded or it will give an error.

roxhead99
June 11th, 2009, 11:23 PM
Example:

ActionScript Code:

// create a circle to click</p>
<p>var circle:Sprite = new Sprite();</p>
<p>circle.graphics.beginFill(0x4080A0);</p>
<p>circle.graphics.drawCircle(50, 50, 25);</p>
<p>addChild(circle);</p>
<p>&nbsp;</p>
<p>circle.addEventListener(MouseEvent.MOUSE_DOWN, mouseDown);</p>
<p>function mouseDown(event:MouseEvent):void {</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;// down, now check for global mouseUp</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;stage.addEventListener(MouseEvent.MOUSE_UP , mouseUp);</p>
<p>}</p>
<p>function mouseUp(event:MouseEvent):void {</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;if (event.target == circle || circle.contains(event.target)){</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;// mouse is up over circle (onRelease)</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;// (if circle is not a DisplayObjectContainer, </p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;// you do not need to use the contains check)</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;}else{</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;// mouse is up outside circle (onReleaseOutside)</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;}</p>
<p>&nbsp;</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;// be sure to clean up stage listener</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;stage.removeEventListener(MouseEvent.MOUSE _UP, mouseUp);</p>
<p>}




Hi senocular. Im a student attempting to build a website in flash for tech. Your tip of the day tutorials have helped a lot so far however theres one bit i cannot get to work.

I have in my site a pop up navigation menu that activates when you click a button. The menu so as to be able to open at any point regardless of the timeline is located in frame 2 of the movie clip where in the button is located.
The problem first was that the menu would open, buttons work, but the menu would never dissapear.
I attempted using you're stage.event listener for mouse up event to return the cilp to frame one so that a click away from the menu would hide it. This worked however the click anywhere function would overwrite the functions of the menus individual buttons.

I then attempted using the above quoted script u supplied in various forms and within the different timelines associated with the menu, ie Movie clip timeline, button timeline, interior buttons timeline. however each time either the buttons would work but not dissappear or the return to frame one would overide the functionality of the buttons.

My last attempt(in which afmenutrans is the movieclip containg the menu buttons):
addChild(afmenutrans)
stage.addEventListener(MouseEvent.MOUSE_UP, mouseUp);
function mouseUp(event:MouseEvent):void {
if (event.target == afmenutrans){
gotoAndStop("rest")

}else{
gotoAndStop("rest");
}

stage.removeEventListener(MouseEvent.MOUSE_UP, mouseUp);
}

seems to work accept the menu doesn't dissapear when returning to frame one, of the movie clip and clicking the button in frame 1 opens another menu over top which in turn doesn't dissappear.

So im sure you're much too busy with continuing adding to ur tip of the days and doing whatever else u do, but if u can revive this old post to help me out that would be much appreciated.

Thanks again for all the great help you have been already.

imjake9
June 14th, 2009, 01:33 PM
The package specific to Flash CS3 classes and Flash CS3 components is named fl. Non-component classes (like Tween) are located within this package directory located in the folder:
<Flash CS3 Install>/<lang>/Configuration/ActionScript 3.0/Classes/

(For an english Windows installation this is C:\Program Files\Adobe\Adobe Flash CS3\en\Configuration\ActionScript 3.0\Classes\)

This directory is specified in the global class path of Flash. You can see this by selecting:
Edit > Preferences > ActionScript (category) > ActionScript 3.0 Settings... (button)

This makes sure any of the classes within that folder will be accessible to all of your Flash CS3 projects. All you need to do is import them appropriately.


I am using Flash CS4, and am looking for the non-component AS3 class files. I have gone to C:\Program Files\Adobe\Adobe Flash CS4\en\Configuration\Actioncript 3.0\, but there is no "Classes" folder inside. Does anyone know where the classes are located in CS4?

gronz
June 15th, 2009, 08:55 AM
When you create a new ActionScript 3 application/movie, you're working with a main timeline as the "root" of your application. This root that *you* as a developer are working with then gets added to the stage when your main timeline i...

First of all, thanks Senocular for providing such extended explanations about the stage, root and MainTimelime combinations. I also read your files at page 15 of this thread how to declare the stage and display objects.
Unfortunately it is a little too hard for me completely understand. I am pretty new to as3.

My problem: I already have a package and several classes outside that package in the same .as, which I got to work.
But I also wanted the header, menubar and a music player removed from the IDE to have everything OOP. But since I have stage aligning properties and an eventlistener I can't get it to work when put in my .as file. I have tried several things but I get a lot of errors like
1120: Access of undefined property stage. etc.

This is what I had in the timeline with the movieclips(music etc.) already placed on the stage:


//Position the menu and set always fullbrowser flash
stage.scaleMode = StageScaleMode.NO_SCALE;
stage.align = StageAlign.TOP_LEFT;
stage.addEventListener (Event.RESIZE, resizeHandler);

resizeHandler (null);
var sw:Number = stage.stageWidth;
var sh:Number = stage.stageHeight;

// initialize sizing for full browser flash
function resizeHandler (event:Event):void
{
music.x = sw-music.width;
tekst.x = sw/2;
header.width = sw;
}
This worked fine in combination with the document class.

But with nothing on the stage, and the music, tekst and header mc's selected for 'export to actionscript' to their (own named) classes I can only make up this and that doesn't work at all:
(a child of Beeldschermvulling is added to the display list inside the package(too much to show here). I guess I am doing something wrong with the order of placing the childs onto the stage?




class Beeldschermvulling extends MovieClip
{
//Position the menu and set always fullbrowser flash
stage.scaleMode = StageScaleMode.NO_SCALE;
stage.align = StageAlign.TOP_LEFT;
stage.addEventListener (Event.RESIZE, resizeHandler);

// initialize sizing for full browser flash


function resizeHandler (event:Event):void
{
resizeHandler (null);
var sw:Number = stage.stageWidth;
var sh:Number = stage.stageHeight;
var music:music = new music();
var tekst:tekst = new tekst();
var header:header = new header();
addChild(music);
music.y=100;

addChild(tekst);
tekst.y=50;

addChild(header);
header.x=0;
header.y=0;
music.x = sw-music.width;
tekst.x = sw/2;
header.width = sw;
}

all imports needed are placed just above these classes. the package file is closed, which means I have several classes underneath the package, but most of them work, only this one gives problems. Thanks for any help or tips...

gronz
June 15th, 2009, 09:22 AM
I guess this thread is too large/complicated to be still very useful for replies from others...
anyways, to my post I just found the answer, I should have placed the stage-properties inside the main function of the public class, not in a subclass....
Really stupid, every time I post something (after trying at least for hours myself) I find the answer within 15 minutes haha.

jotte
July 2nd, 2009, 10:14 AM
Hi!
I am trying to use your code..
var request:URLRequest = new URLRequest("content.swf");
var loader:Loader = new Loader();

But know I want to UnLoad the loader and then reload it with anther content2.swf when a button inside another MC is clicked.

How would that code look like?

/ Thanks

lmonaco99
July 15th, 2009, 03:39 PM
hi senocular
I am having a problem to which the render event my be the solution. here it is
I have a fla with 2 frames. on the 2nd frame is a MovieClip called "_View" , with some textfields in it.
this MoveClip "_View" is has a Class of ViewClass.

after some data from the server loads, the Flash movie goes to the second frame and ViewClass is supposed to populate the textfields with the data. However the data does not appear. It does however appear in the Trace, so i know its there. From within the class, i cannot even manipulate the x position, for example, of the textfields.

if i create an Render handler on instatiation of the classs:
this.addEventListener(Event.RENDER, this.onRender);

i am able to modify various properties of the textfields, but only from within the function:

function onRender(e:Event):void {
trace("IN RENDER: "+e.target); // [object ViewClass]
e.target._modFNameForm.x = 400; // "_modFNameForm" is a textfield on stage
}

as you can imagine, i cannot put my whole class into this function.

how can i successfully do all the data-populating i need to do??

thanks much.
lm

sybersnake
July 25th, 2009, 05:34 PM
Using the new ByteArray (flash.utils.ByteArray (http://livedocs.macromedia.com/flex/2/langref/flash/utils/ByteArray.html)) class in ActionScript 3, you can now easily create deep object copies. By deep, I mean being able to create copies not of just a single object and all its references, but also all the objects it references. This means if you use this method to copy an array which references an object, that object will also be copied as part of the copy procedure. Such a copy (clone) method would look like the following:

function clone(source:Object):* {
var copier:ByteArray = new ByteArray();
copier.writeObject(source);
copier.position = 0;
return(copier.readObject());
}
Note: you may need to import flash.utils.ByteArray;

To use this function simply say:

newObjectCopy = clone(originalObject);
Though this will make a deep copy of your objects, be aware that it does not retain class association. So, if you try to copy a MyClass instance, the copy will no longer be recognized as being of MyClass. This method is best used with generic objects.

I just posted on this topic.

http://sybersnake.com/?p=176

You CAN get a correctly typed object back and I explain why.

Krilnon
July 31st, 2009, 01:41 AM
I just posted on this topic.

http://sybersnake.com/?p=176

You CAN get a correctly typed object back and I explain why.
You're right, you can get one back in some cases. You can also use flash.net.registerClassAlias instead of using the metadata tag.

It's probably good to note that using ByteArray#readObject necessarily calls the registered class's constructor, so it will fail if it has any required parameters. There are also problems when trying to deserialize (or serialize) an instance that has parts that are (or an instance that is itself) unserializable, like a Sprite's graphics.

sybersnake
July 31st, 2009, 01:50 AM
You're right, you can get one back in some cases. You can also use flash.net.registerClassAlias instead of using the metadata tag.

It's probably good to note that using ByteArray#readObject necessarily calls the registered class's constructor, so it will fail if it has any required parameters. There are also problems when trying to deserialize (or serialize) an instance that has parts that are (or an instance that is itself) unserializable, like a Sprite's graphics.

ByteArray#readObject follows all of the rules of AMF Serialization. Like you said, it can't have constructor arguments. This is the reason why in my own framework, this functionality is only implemented in the base 'JKDataObject' class. Following normal practices for data structures clone() should work every time without fail. If its compatible with AMF it works with clone().

ziriguidum
August 28th, 2009, 02:36 PM
senocular you are god.
thank you so much for the explanations.

reid1
August 28th, 2009, 05:12 PM
Hi guys.
I'm trying to make a fade in for my FLV video but I am not sure how I can go about doing that in actionscript 3. I was looking over a sample file that has this fade in effect for the video but it was created in actionscript 2. If I put this code in Actionscript 3 and preview the result, I get a bunch of errors. Does anyone here know how I can convert this code from AS2 to AS3. Thank you guys! The flv video I have is titled "fire4.flv". Here is the code that I have which works in AS2 but not AS3:

import mx.transitions.*;
var netConnection:NetConnection = new NetConnection();
netConnection.connect(null);
var netStream:NetStream = new NetStream(netConnection);
cpVideo.attachVideo(netStream);
netStream.play("fire4.flv");
function fadeOut() {
new Tween(cpVideo, "_alpha", Strong.easeOut, 100, 0, .5, true);
}
setTimeout(fadeOut,1000);

bins2008
September 16th, 2009, 11:03 PM
Hello, this is AS 2.0, how i can change to AS 3.0? the "_root.Line" is a movie clip..

on (rollOver) {
_root.Line.onEnterFrame = function() {
_root.Line._x = _root.Line._x+(389-_root.Line._x)/8;
_root.Line._width = _root.Line._width+(68-_root.Line._width)/8;
};
}

also i wanna chance this into circular movement..

Thanks..

Hardrun
September 18th, 2009, 12:43 AM
Thanks for posting this Sen . (http://www.watchgossipgirlonline.tv). (http://www.watchthevampirediaries.org)

tinkutr
September 21st, 2009, 01:04 AM
WOW this is a great reference thread.

ellewood631
November 10th, 2009, 02:19 AM
Nice to have an AS 3 thread. Maybe whole Flex/AS3 forum would be usefull as it seem to spred a lot.

dr_tchock
December 1st, 2009, 12:48 PM
Nice to have an AS 3 thread. Maybe whole Flex/AS3 forum would be usefull as it seem to spred a lot.

Like this?

http://www.kirupa.com/forum/forumdisplay.php?f=141

littlephoenix
December 18th, 2009, 05:28 PM
awesome thread, my question is, do browsers now pick up text from flash sites and index them, for what i heard, flash cs4 was going to incorporate this, i guess thatis why im stillstaying away from flash because of this, anyone? thanks

stalker
January 8th, 2010, 08:56 AM
Hi!

Do you have any idea what the oposit of "is" could be? All i can do no is check if something "is", and then write the relevant code, to the else block. This is kind of lame :)

Thanks a lot! :)

oybrator
January 8th, 2010, 09:34 AM
Hi!

Do you have any idea what the oposit of "is" could be? All i can do no is check if something "is", and then write the relevant code, to the else block. This is kind of lame :)

Thanks a lot! :)

Yeah, something like "not" or "isNot" would be great for readablility. Sadly that doesn't work, but !(value is String) does (where the part after "is" could be any type obviously).

if (value isNot String)... Neat!

bhjodokast
January 15th, 2010, 09:56 AM
Yeah, something like "not" or "isNot" would be great for readablility. Sadly that doesn't work, but !(value is String) does (where the part after "is" could be any type obviously).

if (value isNot String)... Neat!

It's a 'feature' of languages like VB.NET to be more readable with their operators.

For ActionScript operators, check out http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/operators.html

mike_mike
January 16th, 2010, 06:44 PM
Hi there!

Check at my new tutorial and download its source of a OOP Flash website using AS3 external classes.

No more code in the timeline!!!

Check here: http://wordpress.mikeland.us/2010/01/16/simple-object-oriented-website-layout-as3/

Hope you enjoy!!

Mike

ayounas
January 18th, 2010, 05:01 PM
Hmmmmmmmmmmmmmmm...

vijay7002
January 19th, 2010, 02:22 AM
Hi,
You can check example of change frame rate from this tutorials:
http://webmuni.com/blog/

Thanks,


Using ActionScript 3, you can dynamically change the frame rate of your movie using the Stage class.

The Stage class (flash.display.Stage (http://livedocs.macromedia.com/flex/2/langref/flash/display/Stage.html)) is the class assigned to the stage object which is accessible from your main movie sprite/movie clip (or others within the same security sandbox) using the stage property. The stage object has a frameRate property which can contain any value between 0.01 and 1000 and determines the frame rate at which the Flash player plays back your movie. Changing this value lets you change the frame rate at runtime.

ActionScript Code:

// change frame rate to 12 fps:
stage.frameRate = 12;

Swooter
January 20th, 2010, 05:47 AM
include "scripts/myscript.as"

Is the semicolon bug fixed in AS3?

AS2:

#include("some.as") // works
#include("some.as"); // doesn't work

_kp
January 20th, 2010, 08:05 AM
Is the semicolon bug fixed in AS3?

AS2:

#include("some.as") // works
#include("some.as"); // doesn't work

Doesn't really look like a bug to me. Anyway #include has been deprecated in as3.

felipegm
January 20th, 2010, 07:02 PM
When loading external movies or other display content (like images) into the Flash Player with ActionScript 3, you load the content into a Loader (http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/display/Loader.html) instance. Loaders provide containers for the external content to exist. No longer can you load external content into any movie clip, nor can you load SWFs into another level as levels no longer exist in ActionScript 3; you have to use a Loader instance.



After loading the swf, how can I control it's timeline using a button at maintimeline of root?

Thanks

littlephil
January 26th, 2010, 03:10 PM
nope, im making a flash app for my site but cant get the following button to work goin from one scene to the next, any ideas?

code:
startbutton.addEventListener(MouseEvent.MOUSE_DOWN , mouseDownHandler);
function mouseDownHandler(event:MouseEvent):void {
gotoAndPlay(1);
}

Phil M

http://www.bigpenguin.co.uk (http://www.bigpenguin.co.uk/)

FlashDave
February 5th, 2010, 01:59 AM
Why do you keep talking about CS3, when ever I start reading, and what I'm reading is aplied to CS3, I just wonder?
There are some changes in CS4 that are not compatible with CS3?

David H
painterdave22@wildblue.net

kemronhits
March 3rd, 2010, 01:36 AM
I recently know about as2 and as3.
The startDrag function has changed a bit since as2. Where it used to take 0, 1 or 5 arguments it now takes 0, 1 or 2.
as2:
myMC.onPress = function () {
this.startDrag(lockCenter, left, top, right, bottom);
}
myMC.onRelease = function () {
this.stopDrag();
}
In as2 in as3 there are some problem with dragging on a low framerate.To overcome this you can use updateAfterEvent().

aaaidan
March 14th, 2010, 06:50 PM
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).


I don't wanna be too much of a smug little smartypants, but isn't it the dispatcher that internally requires a reference to the listener?

one giant media
March 18th, 2010, 03:21 AM
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.

Wow - you're right, you can't iterate through properties of a user-defined class instance unless the class is dynamic- but after some testing I'm not getting any iteration for the instance properties on my custom class instance (Dynamic class that extends Object).... will this only work on properties that are applied to a dynamic class that aren't listed in it? Is there a way to iterate dynamically through public class members that are defined in the class?

ChrisWallaceTSG
April 6th, 2010, 12:23 PM
Here's a tip: If you're not using subversion (I like 'versions' as a client), START.

imfragnot
April 29th, 2010, 08:54 AM
Is navigateToURL also part of this list of methods which inherit directly from the Object Class?



hasOwnProperty
isPrototypeOf
propertyIsEnumerable
setPropertyIsEnumerable
toString
valueOf


I'm using the following code to override the the navigateToURL method and the override keyword must be removed for it to work:



package {

import flash.display.MovieClip;
import flash.events.MouseEvent;
import flash.net.navigateToURL;
import flash.net.URLRequest;


public class MyMovie extends MovieClip {

public function MyMovie() {

myButton.addEventListener(MouseEvent.CLICK, handleMyButtonClick);

}
public function navigateToURL (request:URLRequest, window:String = null):void {
trace("bang!");
flash.net.navigateToURL(request, window);
}

private function handleMyButtonClick (e:MouseEvent):void {

navigateToURL(new URLRequest("http://www.msnbc.com"));

}

}

}
Im confused as to why this works. Thanks.


Also be aware that override is not needed for methods inherited directly from the Object class. These include:

hasOwnProperty
isPrototypeOf
propertyIsEnumerable
setPropertyIsEnumerable
toString
valueOf

These methods are added dynamically and are not part of the actual class definition. The override keyword is to be used only with methods which are part of a class's original definition.

Krilnon
May 7th, 2010, 12:55 PM
Is navigateToURL also part of this list of methods which inherit directly from the Object Class?

It's not; it's not even a method per se. It's a so-called "package function", or a function that's the one externally visible definition in a package block. If it were written in ActionScript, it'd be declared kind of like this:
package flash.net {
public function navigateToURL(url:URLRequest, target:String){ … }
}

kadaj
May 12th, 2010, 10:14 AM
Consider a case where there are two classes called Main, and Other. The class Main is the Document Class, which has instantiated an object of the class Other. Here for the Class Other to access the methods of the class Main, can be easily done by creating an instance which is a static variable of the class Main which can be called only through the class. Static variables are associated with a class and not with instance of the class. Here we are giving a global access.
See example below:


//Main.as
package {

import flash.display.Sprite;

public class Main extends Sprite
{
public static var mainInstance:Main;
private var _child:Other;

public function Main()
{
mainInstance = this;
_child = new Other();
}

public function foo():void
{
trace("hello from document class");
}
}
}




//Other.as
package {

import flash.display.MovieClip;

public class Other {

public function Other()
{
Main.mainInstance.foo();
}
}
}

You can use getter if you don't want to expose the variables. This is used with the singleton design pattern. Example where a singleton pattern is used is in case of mouse pointer. Here only one mouse pointer will be used. So there isn't a need for having multiple instances of the class. So we can use static methods that's associated with the class rather than with each of its instances.

IQpierce
May 30th, 2010, 01:07 AM
With regards to senocular's post titled "Flash CS3: Frame Navigation and Child Access".

I've tried the workaround described by senocular and found it to be unreliable. I've found that the only reliable way to access the child in these cases is to attach a temporary listener to the onEnterFrame event, and actually wait until the desired fields don't resolve to "null."

I wrote a function to allow for doing this while still keeping your code clean and easy to follow, and blogged about the topic in a bit more detail, here:
http://www.deepplaid.com/blog/?p=157

Hope someone finds this useful.

m4rt5
June 1st, 2010, 04:58 PM
Is there a way to do the same but to stop an animation of the as3 while clicking a button from the as2 loaded file?

txs

martin


The ActionScript virtual machine that runs ActionScript 3 code (AVM2) is completely different from the ActionScript virtual machin that runs ActionScript 1 and ActionScript 2 code (AVM1). Because of this, you cannot call commands in an AVM1 movie from and AVM2 movie or vise versa. The virtual machines just are not compatible in that respect and mostly run in their own kind of shell that allows it to only interact with code being played back in that same virtual machine. What that boils down to is that ActionScript 3 cannot talk to AS1 or AS2 - at least not directly.

One thing these two virtual machines have in common is their implementation of LocalConnection. Both virtual machines deal with local connections in essentially the same way - enough that local connections in AVM1 can receive events from AVM2 and vise versa. So should you come into a situation where you would need a movie published in ActionScript 3 to communicate with a movie published in ActionScript 1 or 2, using local connection is the way to go.

LocalConnection AS2 (http://livedocs.macromedia.com/flash/8/main/00002338.html)
LocalConnection AS3 (flash.net.LocalConnection) (http://livedocs.macromedia.com/flex/2/langref/flash/net/LocalConnection.html)

Example:

// ActionScript 2 file, AS2animation.fla
// one movie clip animation named animation_mc on the timeline

// local connection instance to receive events
var AVM_lc:LocalConnection = new LocalConnection();

// stopAnimation event handler
AVM_lc.stopAnimation = function(){
animation_mc.stop();
}

// listen for events for "AVM2toAVM1"
AVM_lc.connect("AVM2toAVM1");

// ActionScript 3 file, AS3Loader.fla

// local connection instance to communicate to AVM1 movie
var AVM_lc:LocalConnection = new LocalConnection();

// loader loads AVM1 movie
var loader:Loader = new Loader();
loader.load(new URLRequest("AS2animation.swf"));
addChild(loader);

// when AVM1 movie is clicked, call stopPlayback
loader.addEventListener(MouseEvent.CLICK, stopPlayback);

function stopPlayback(event:MouseEvent):void {
// send stopAnimation event to "AVM2toAVM1" connection
AVM_lc.send("AVM2toAVM1", "stopAnimation");
}

The AS3 movie loads the AS2 movie into a Loader instance and places it on the screen. As it plays, the user can click the animation which calls stopPlayback sending the "stopAnimation" event to the local connection named "AVM2toAVM1". The AS2 movie is then able to receive that event in its stopAnimation event handler and tell the animation_mc clip to stop.

uacomp
June 8th, 2010, 11:04 AM
ActionScript 3 no longer has a duplicateMovieClip method for MovieClip instances (or any DisplayObject instances). Instead, it's suggested that you just create a new instance of the display object you wish to duplicate using its constructor. This, however, is not the same as duplicateMovieClip, and, really, is more like using AS1 and AS2's attachMovieClip. For a more accurate representation of duplicateMovieClip in AS3, consider the following function:

package com.senocular.display {

import flash.display.DisplayObject;
import flash.geom.Rectangle;

/**
* duplicateDisplayObject
* creates a duplicate of the DisplayObject passed.
* similar to duplicateMovieClip in AVM1
* @param target the display object to duplicate
* @param autoAdd if true, adds the duplicate to the display list
* in which target was located
* @return a duplicate instance of target
*/
public function duplicateDisplayObject(target:DisplayObject, autoAdd:Boolean = false):DisplayObject {
// create duplicate
var targetClass:Class = Object(target).constructor;
var duplicate:DisplayObject = new targetClass();

// duplicate properties
duplicate.transform = target.transform;
duplicate.filters = target.filters;
duplicate.cacheAsBitmap = target.cacheAsBitmap;
duplicate.opaqueBackground = target.opaqueBackground;
if (target.scale9Grid) {
var rect:Rectangle = target.scale9Grid;
// WAS Flash 9 bug where returned scale9Grid is 20x larger than assigned
// rect.x /= 20, rect.y /= 20, rect.width /= 20, rect.height /= 20;
duplicate.scale9Grid = rect;
}

// add to target parent's display list
// if autoAdd was provided as true
if (autoAdd && target.parent) {
target.parent.addChild(duplicate);
}
return duplicate;
}
}


with this method all actionsctipt code in original movieclip and his childs doesn't work. maybe, do you know how to solve this issue?

cjke.7777
June 13th, 2010, 04:51 AM
Hi - thanks as always for the great and ongoing information but I need to clarify something.

The Key.isDown method posted here - should I be using this, or the one on the senocular.com site? The one on the site uses flash_proxy, this one doesn't.

Any recommendations?

shivnikum
June 30th, 2010, 02:23 AM
Hello Senocular,

I am trying to use below code for duplicating display object but its giving me 1118: Implicit coercion of a value with static type flash.display:DisplayObject to a possibly unrelated type flash.display:Sprite.

var solt:Sprite = new Sprite();
addChild(solt);
var newInstance:Sprite = duplicateDisplayObject(this.slot_mc, true);
newInstance.x += 100;

Please have a look and let me know where i am wrong

Thanks,

S Nik

sharat.achary
July 7th, 2010, 07:22 AM
" be aware that it does not retain class association " - as you said, can we type cast the resultant copied object with the class we were concerned...

var copyObj:MyClass = clone(cpOBJ) as MyClass;

Woudl this do ? Just sharing my query as we use the same for the converting the target or currentTarget objects received by the event object in the EventHandler method...

private function updateWindow_EH(e:Event):void{
var details:DetailsObj = e.target as DetailsObj
.
.
.
}

Please do correct me.


Thanks & Regards
Sharat Achary

grandpaw broon
July 7th, 2010, 06:17 PM
Sen? Can you do this thread again but with 10.1? :P

kalani96746
July 23rd, 2010, 02:57 PM
Just a note. You can't seem to trigger a stage.invalidate() during a handler for Event.RENDER. Since its it the same pass it doesn't work and the event doesn't trigger.

In a Event.RENDER handler I was adding an Event.RENDER listener to a sub movieclip and triggering a gotoAndStop() then a stage.invalidate(). What I needed to do to get it to work is add an Event.ENTER_FRAME listener then in the ENTER_FRAME listener add an Event.RENDER listener, then handle it..

Complicated mess of sorts but if you are trying to do this in a render event listener this add an enter_frame listener, then in the enter_frame add a render event listener. I don't know if I sound like I'm making sense but thats what you do.


ActionScript has long since relied on the enterFrame (onEnterFrame) event for time-based actions, especially animation and actions relating to frame playback. In comparison, Director's Lingo language has, not only an enterFrame event, but two other frame events, prepareFrame and exitFrame. Though ActionScript 3 has not aquired prepareFrame or exitFrame, it has gained a new frame event, render, or Event.RENDER (flash.events.Event.RENDER (http://livedocs.macromedia.com/flex/2/langref/flash/events/Event.html#RENDER)).

The render event in AS3 is a frame event that occurs after enterFrame (flash.events.Event.ENTER_FRAME (http://livedocs.macromedia.com/flex/2/langref/flash/events/Event.html#ENTER_FRAME)) allowing one more chance to do what you need to do before the screen updates its display.

Unlike enterFrame, however, the render event will not be called unless the display object using it is attached to a stage (or in any display list attached to the stage). Also, render is not automatically called every frame, even if attached to the stage. In order for render to be called for the current frame, you must make a call to stage.invalidate() (flash.display.Stage.invalidate() (http://livedocs.macromedia.com/flex/2/langref/flash/display/Stage.html#invalidate%28%29));

Ex:

var sprite:Sprite = new Sprite();
stage.addChild(sprite);

sprite.addEventListener(Event.ENTER_FRAME, enterFrame);
sprite.addEventListener(Event.RENDER, render);
stage.addEventListener(MouseEvent.CLICK, click);

function enterFrame(event:Event):void {
trace("enter frame");
}
function render(event:Event):void {
trace("render");
}
function click(event:MouseEvent):void {
trace("click");
stage.invalidate();
}
Output:
enter frame
enter frame
enter frame
click
enter frame
render
enter frame
enter frame
enter frame
enter frame
...

shubhram
July 30th, 2010, 08:19 AM
Can Any one help me in making .. a tool for audio/video recording through fms with replay option!

looking fr d help

Thanks
shubhram

flashjr
August 5th, 2010, 06:06 AM
how can is use the away 3d in flash and how can I integrate my own 3d layout with using away 3d are any other

kadaj
September 1st, 2010, 04:44 AM
To see the generated actionscript classes from your mxml code give -keep as additional compiler arguments.
eg: In Flash Builder select Project->Properties->Flex Compiler and in the Additional compiler arguments will look:


-locale en_US -keep

rimacy
September 16th, 2010, 01:09 PM
this seems pivotal what does it grant player by passing it map in this way... what am i saying by doing this?
var map = new Map(); var player = new Player(map);

kadaj
October 5th, 2010, 05:29 AM
Consider this normal example:



function greetings():void {
trace("Hello World");
}

greetings();

This will display "Hello World".

The above example can be written in more elegant way (i.e., self invoking the function) as:


(function greetings():void {
trace("Hello World");
})();

You get the same result. So the format is:


(f)();


Another example:


(function greetUser(name:String):void {
trace( "Hello " + name );
})("Awesome");

You pass an argument during self invocation.

[edit]
However one important thing you must consider is the scope.

(function greetUser(name:String):void {
trace( "Hello " + name );
})("Awesome");

greetUser("Foo"); //will result in error because its not global

So note that.
:flower:

kadaj
October 5th, 2010, 06:39 AM
Function Arguments in Depth

Function which takes infinite arguments


function infiniteArgs(...args):void {
trace(args);
}

infiniteArgs( 1, 2 );
infiniteArgs( 1, 2, 3, 4, 5 );
infiniteArgs( 1, 2, 3, 4, 5, 6, 7 );
infiniteArgs( 'a', 'b', 'c' );


Another method without all this hassle is to do like the below. I recommend this instead of the above method:


var inf:Function = function():void {
trace(arguments);
}

inf( 1, 2, 3, 4 );
inf( 'a', 'b' );


Arguments array


function foo(a:int, b:int, c:int):void [
trace(arguments); //displays the arguments passed
}
foo( 1, 2, 3 );
foo( 0, 10, 110 );

It will display the arguments passed into the function.
Now you can use arguments.length, arguments[0] etc.


function foo(a:int, b:int, c:int):void {
trace( "args: " + arguments );
trace( "len: " + arguments.length );
trace( "arguments[2]: " + arguments[2] );
}
foo( 1, 2, 3 );
foo( 1, 10, 110 );


When using mutliple parameters the arguments are referred by the variable that you put after the 3 dots. i.e:


function foo(...myCoolArgs):void {
//instead of myCoolArgs if you gave arguments you'll get undefined error.
trace( "args: " + myCoolArgs );
trace( "len: " + myCoolArgs.length );
}


Passing arguments to another function
You have a function which received arguments. You need to send those arguments to another function as arguments itself instead of an array. For that you can use the 'apply' function.


//normal situation
function fooA(...myCoolArgs):void {
trace( "args: " + myCoolArgs );
trace( "len: " + myCoolArgs.length ); //you get 5
fooB( myCoolArgs );
}

function fooB(...args):void {
trace( "args: " + args );
trace( "len: " + args.length ); // you get 1 instead of 5
}

fooA( 0, 1, 2, 3, 4 );

Its passed as an argument array. So what you do is:


function fooA(...myCoolArgs):void {
trace( "args: " + myCoolArgs );
trace( "len: " + myCoolArgs.length ); //you get 5
fooB.apply( this, myCoolArgs ); //pass it like this
}

function fooB(...args):void {
trace( "args: " + args );
trace( "len: " + args.length ); // now you get 5
}

fooA( 0, 1, 2, 3, 4 );


More cooler version:


var fooA:Function = function():void {
trace( "args: " + arguments );
trace( "len: " + arguments.length );
fooB.apply( this, arguments );
}

var fooB:Function = function():void {
trace( "args: " + arguments );
trace( "len: " + arguments.length );
}

fooA( 0, 1, 2, 3, 4 );
fooA( 'a', 'b', 'c' );

:snooze:

kadaj
October 5th, 2010, 07:54 AM
You must be familiar with recursion with normal functions, i.e a function calling itself. An anonymous function is a function without a name. So to use recursion in an anonymous function you call the arguments.callee() to refer to the anonymous function.
If its a normal function we can call that function using its name. Anonymous function don't have name, but you can refer the function using the callee method.

How to approach recursion?
The key idea to recursion is the terminating condition. First you need to figure out when the function should terminate. Then you think on how to generalize. Means first you look at when the factorial function say fact(n) should terminate, .i.e, when n==1.

A normal function that computes factorial (I'm choosing factorial because its simple, and easy to understand) can be like:


function fact(n):int {
if( n == 1 )
return 1;
else return n * fact( n-1 );
}
trace(fact(5));


In terms of anonymous function:


var fact:int = (function(n):int {
if( n==1 )
return 1;
else return n * arguments.callee( n-1 );
})(5);

trace(fact);

:hr:

marilee2309
October 27th, 2010, 08:21 AM
Using ActionScript 3, you can dynamically change the frame rate of your movie using the Stage class.

The Stage class (flash.display.Stage (http://livedocs.macromedia.com/flex/2/langref/flash/display/Stage.html)) is the class assigned to the stage object which is accessible from your main movie sprite/movie clip (or others within the same security sandbox) using the stage property. The stage object has a frameRate property which can contain any value between 0.01 and 1000 and determines the frame rate at which the Flash player plays back your movie. Changing this value lets you change the frame rate at runtime.


// change frame rate to 12 fps:
stage.frameRate = 12;
Thanks for sharing !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
_______________________________________________
Kanyakumari (http://www.sangamgrouphotels.com) | Kanyakumari Hotels (http://www.sangamgrouphotels.com) | Kanyakumari Rock Memorial (http://www.sangamgrouphotels.com)

kadaj
November 8th, 2010, 11:59 PM
Declare multiple variables in one line:

var i:int=0, j:int=0, k:int=0;

flashvideo
November 26th, 2010, 04:33 AM
really very nice.http://flashvidplayer.com/smileynormal.ico

Rackdoll
November 26th, 2010, 07:11 AM
assign multiple vars with same value, ... the short way.



var one:int=0, two:int=0, three:int = 0;
one = two = three = 1;

hooligan
January 20th, 2011, 08:32 PM
Hey senocular,

This might be old news but I just tried your duplicateDisplayObject method with the BulkLoader classes and it keeps returning an empty movieclip.

In BulkLoader I load a swf and get it as a MovieClip

var mc:MovieClip = loader.getMovieClip("box.swf");

then when I try,

addChild(duplicateDisplayObject(mc)); or

var newMc:MovieClip = duplicateDisplayObject(mc);
addChild(newMc);

It just return a blank movieclip with no graphics.

I know the swf loads properly because if I add the mc to the stage I see the graphics. I just need to be able to make multiple copies of the object. I don't want to have to load a new copy for every duplicate.

sivavinayagam
March 8th, 2011, 11:30 PM
how to post my question in kirupa,
please send replay

sivavinayagam
March 8th, 2011, 11:36 PM
what is different between AS3 and AS2?

jloa
March 9th, 2011, 11:26 AM
Never use indexOf when making array unique sort. Always use dictionaries or objects.

WRONG:


function arrayUniqueIndex(s:Array):Array
{
var n:int = s.length;
var uniq:Array = new Array();
for(var i:int = 0; i < n; i++) if(uniq.indexOf(s[i]) < 0) uniq.push(s[i]);
return uniq;
}
CORRECT:


function arrayUniqueObj(s:Array):Array
{
var n:int = s.length;
var uniq:Array = new Array();
var obj:Object = new Object();
for(var i:int = 0; i < n; i++) if(!obj[s[i]]) { obj[s[i]] = true; uniq.push(s[i]); }
return uniq;
}
function arrayUniqueDict(s:Array):Array
{
var n:int = s.length;
var uniq:Array = new Array();
var dict:Dictionary = new Dictionary(true);
for(var i:int = 0; i < n; i++) if(!dict[s[i]]) { dict[s[i]] = true; uniq.push(s[i]); }
return uniq;
}
Proof:


unique.sort benchmark | core2duo 3ghz, 4gb ddr2 ram, win 10.2.152.26 debug
array -> 500000 elements (20 cycles)
--------------------------------
object | dict | indexOf
--------------------------------
18 ms | 16 ms | 316 ms
16 ms | 16 ms | 328 ms
16 ms | 16 ms | 317 ms
17 ms | 15 ms | 314 ms
17 ms | 15 ms | 315 ms
16 ms | 16 ms | 315 ms
17 ms | 15 ms | 314 ms
17 ms | 15 ms | 314 ms
16 ms | 16 ms | 315 ms
16 ms | 17 ms | 314 ms
16 ms | 16 ms | 314 ms
16 ms | 16 ms | 315 ms
16 ms | 16 ms | 314 ms
16 ms | 16 ms | 316 ms
16 ms | 16 ms | 317 ms
17 ms | 16 ms | 314 ms
16 ms | 16 ms | 315 ms
16 ms | 16 ms | 314 ms
17 ms | 15 ms | 314 ms
16 ms | 16 ms | 318 ms

--------------------------------
avg results:
object | dict | indexOf
--------------------------------
16 ms | 15 ms | 315 ms
--------------------------------
Benchmark >> http://pastebin.com/8tJbGGX1

Shaedo
April 9th, 2011, 10:47 PM
I find the opposite with them all being very close but unique index (still) being the quickest. So using uniqueIndex is, for me, a tiny bit faster and a tiny bit more legible. I'd also guess (can't be bothered to check) that it uses a bit less memory as your not creating the other variables.

Note of course I used very small arrays with only a few cycles compared to what jloa used.

Here is the code I used, feel free to copy and paste and test it on your own system:


var a:Array; // array to sort
var t,c,i:int; // time, number of iterations, counter
c= 100000;

t=getTimer();
for (i=0;i<c;i++)
{
a=['a','a','b','b','c','c'];
a=arrayUniqueIndex(a);
}
trace('unique index:' + (getTimer()-t)); // 346


t=getTimer();
for (i=0;i<c;i++)
{
a=['a','a','b','b','c','c'];
a=arrayUniqueDict(a);
}
trace('arrayUniqueDict:' + (getTimer()-t)); // 419

t=getTimer();
for (i=0;i<c;i++)
{
a=['a','a','b','b','c','c'];
a=arrayUniqueObj(a);
}
trace('arrayUniqueObj:' + (getTimer()-t)); // 358


function arrayUniqueDict(s:Array):Array
{
var n:int = s.length;
var uniq:Array = new Array();
var dict:Dictionary = new Dictionary(true);
for(var i:int = 0; i < n; i++) if(!dict[s[i]]) { dict[s[i]] = true; uniq.push(s[i]); }
return uniq;
}

function arrayUniqueObj(s:Array):Array
{
var n:int = s.length;
var uniq:Array = new Array();
var obj:Object = new Object();
for(var i:int = 0; i < n; i++) if(!obj[s[i]]) { obj[s[i]] = true; uniq.push(s[i]); }
return uniq;
}

function arrayUniqueIndex(s:Array):Array
{
var n:int = s.length;
var uniq:Array = new Array();
for(var i:int = 0; i < n; i++) if(uniq.indexOf(s[i]) < 0) uniq.push(s[i]);
return uniq;
}

92Garfield
April 13th, 2011, 08:05 AM
...The following recreation of the Key class takes that into consideration...
About the Key class.

When I have a class using the Key class and create an instance of it.

May I remove the instance by setting it to null and removing from display list as usual? I'm afraid it wouldn't work because of the reference to stage.

embarker
April 18th, 2011, 03:23 PM
ActionScript 3 now embraces a much more strict enforcement of encapsulation - or maintaining individual isolation within classes. A primary example of this is root and stage access. Now, not every class can access the root or stage directly, not without being given an explicit reference or, for display objects, by being added to the stage's display list from an outside source (or outside reference).

What this means is a change of how you need to approach programming with Flash ActionScript 3.0. Now, instead of taking the approach of Inside Looking Out you need to think in the way of Outside Looking In.

Now we're talking in a language I can understand.
Excellent post man.

lauraegg
May 22nd, 2011, 08:20 PM
// when AVM1 movie is clicked, call stopPlayback
loader.addEventListener(MouseEvent.CLICK, stopPlayback);


I see that I get a mistake when i take the stopPlayback function out of the one that contains it (i.e. if i want to make it public)

TypeError: Error #1009:
Is there something I am not getting?
Thanks

princessjussel
May 23rd, 2011, 12:16 AM
Example:

var loader:URLLoader;
// ...
loader = new URLLoader();
loader.addEventListener(Event.COMPLETE, xmlLoaded);

var request:URLRequest = new URLRequest("file.xml");
loader.load(request);
//...
function xmlLoaded(event:Event):void {
var myXML:XML = new XML(loader.data);
//...
}

how will I be able to duplicate a loaded data?

ataktos_gr
May 24th, 2011, 08:49 AM
Hello to everybody!! How can I create a Last scene button in project of an application?
I want when I press it went me to last scene I had saw. If I saw 2-6-7-9 scenes and now I'm in 9scene, in press 2times the button, went me to 6 scene.

Can somebody help me?
Thanks!
Sotiris.

genlife
September 7th, 2011, 05:04 AM
Do you want to pass parameters with event listeners? Just do this...

addEventListener(Event, function(){yourFunction(parameters)},false,0,true) ;

Only do this if you know you will not need to remove it later, cause you can't remove this event listener.

kaz88
October 22nd, 2011, 01:04 AM
Detecting a mouseUp Outside doesn't work in Safari, any idea how to get an onReleaseOutside triggered when the user releases outside of the flash window?

MJTheOne
October 23rd, 2011, 04:50 PM
My tip of the day would be, even if you firmly believe something won't work. Still try it, sometimes it will work... :P

arundracula
November 3rd, 2011, 02:01 AM
You might have seen numerous number rounding tricks. But sometimes flash doesn't behave correctly.
For eg:



for(var i=0;i<360;i+=3.6){
trace(i);
}


This will output numbers like
338.4000000000002
342.0000000000002
345.60000000000025 etc..

From this link: http://kb2.adobe.com/cps/155/tn_15542.html
It will produce
72
75.59
79.19

So, when I required to draw a circle with rulers, I wrote this. This may help some of you.


function roundToDecimalPlaces(n:Number,d:Number):Number
{
return Number(String(Math.round(n*Math.pow(10,d))/Math.pow(10,d)).substr(0,String(n).indexOf(".")+((d==0)?-1:d)+1));
}


which returns
72
75.6
79.2

even if 'd' is above 2.

tbo
November 13th, 2011, 08:19 PM
[FLASH IDE]

In a MovieClip timeline, if you have two frame labels on the same frame number:

Example:
(Layer 1 frame10 = "a")
(Layer 2 frame10 = "b")
[note layer1 is above layer2]


mc.gotoAndStop(10);
trace(mc.currentFrameLabel); // a
trace(mc.currentLabel ); // b


What is one reason you could need this?

I needed to flag certain frames to draw from later on, but do not want to disrupt the animation labels, which may fall on the same frame.

mottatta
November 24th, 2011, 10:42 AM
Hi. I was looking for solution on the 'isDown' problem with flash AS 3.0 and I found this site. I created a Key.as class file and saved it in same dir as my .fla file. Try to test if a right arrow is pressed as shown in the comment of the class definition Key.as. Here is what my .fla file looks like:

import Key;
import flash.ui.Keyboard;
import flash.display.Stage;




Key.initialize(stage);
if (Key.isDown(Keyboard.LEFT)) {
// Left key is being pressed
trace("M'Kay");
}

But when I run and I press right arrow I don't get 'M'kay' message. Please if you could tell me what I do wrong. Thank you very much and have a nice day! :-)

ilhanspage
November 30th, 2011, 04:47 AM
PLEASE HELP ME!!!!!!!!!!!!!!!!!!!!!!!1
<data>
<MsgBox>
<dunyaMc>

<ozellik>
çekilecek veriler
<ozellik>
<marsMc>
<ozellik>
çekilecek veriler
<ozellik>

</marsMc>
</MsgBox>
</data> /// BÖYLE DEVAM EDİYOR...



var msgBoxReq:URLRequest = new URLRequest("XML/Main.xml");
var msgBoxLdr:URLLoader = new URLLoader();
msgBoxLdr.load (msgBoxReq);
var xml:XML = new XML();;
var msgBoxTxt:TextField = new TextField();
msgBoxLdr.addEventListener (Event.COMPLETE , onMsgBoxLdrComplete);


function onMsgBoxLdrComplete (evt:Event):void
{
xml = XML(evt.target.data);


func ();


}


function func ():void
{

//dunyaMc
dunyaMc.addEventListener (MouseEvent.MOUSE_OVER , onMcOver);
dunyaMc.addEventListener (MouseEvent.MOUSE_OUT , onMcOut);
dunyaMc.buttonMode = true;


//marsMc
marsMc.addEventListener (MouseEvent.MOUSE_OVER , onMcOver);
marsMc.addEventListener (MouseEvent.MOUSE_OUT , onMcOut);
marsMc.buttonMode = true;


//saturnMc
saturnMc.addEventListener (MouseEvent.MOUSE_OVER , onMcOver);
saturnMc.addEventListener (MouseEvent.MOUSE_OUT , onMcOut);
saturnMc.buttonMode = true;


//uranusMc
uranusMc.addEventListener (MouseEvent.MOUSE_OVER , onMcOver);
uranusMc.addEventListener (MouseEvent.MOUSE_OUT , onMcOut);
uranusMc.buttonMode = true;



}
function onMcOver (evt:MouseEvent):void
{
msgBox.visible = true;
msgBox.graphics.clear ();
//msgBox.graphics.lineStyle (1,0x000000,.3);
msgBox.graphics.beginFill (0xffffff,1);
msgBox.graphics.lineTo (0,0);
msgBox.graphics.lineTo (200,0);
msgBox.graphics.lineTo (200,100);
msgBox.graphics.lineTo (30,100);
msgBox.graphics.lineTo (20,110);
msgBox.graphics.lineTo (10,100);
msgBox.graphics.lineTo (0,100);

addChild (msgBox);
var msgBoxTxt:TextField = new TextField();

msgBox.addChild(msgBoxTxt);

msgBoxTxt.text =xml.MsgBox.evt.target.ozellik;//// ERRORRRRRR....






}
function onMcOut (evt:MouseEvent):void
{
msgBox.visible = false;


}