AS3: addChild()

I'm just getting into AS3 and it is making me crazy. All over
the place (help files etc.) I see code like this.
addChild(myLoader);
Where myLoader is an instance of the Loader class. But it
could be a Sprite or something else. But to what are we adding the
child? It seems that Loader inherits like this (has anybody else
noticed that copying from the help files never seems to work on the
first try?):
Loader DisplayObjectContainer InteractiveObject DisplayObject
EventDispatcher Object
And it seems that addChild() is inherited from the
DisplayObjectContainer class. So is the addChild adding the loader
to itself?

When you create a DisplayObject using the new operator, it
has no parent.
The addChild method allows you to change the objects
parentage -- a real
improvement for Flash.
Try this snippet in the timeline:
import flash.display.*;
import flash.events.MouseEvent;
var s1:Sprite = new Sprite();
var s2:Sprite = new Sprite();
s1.x = 10;
s1.y = 10;
s2.x = 200;
s2.y = 10;
this.addChild(s1);
this.addChild(s2);
var rect:Shape = new Shape();
rect.graphics.beginFill(0xff0000);
rect.graphics.drawRect(0,0,100,100);
rect.graphics.endFill();
rect.x = 20;
rect.y = 20;
s2.addChild(rect);
s2.addEventListener(MouseEvent.CLICK, clickHandler);
s1.addEventListener(MouseEvent.CLICK, clickHandler);
function clickHandler(event:MouseEvent){
if(event.target == s1){s2.addChild(rect);}
else{s1.addChild(rect);}
trace(rect.parent.name)

Similar Messages

  • AS3 addChild() to what????

    I'm trying to figure out this new DisplayObject list and
    stuff. I wanted to make some random boxes and put them on the stage
    – which works great. Then I decided I would like to drag them
    around – again no problem. Then I decided I would like the
    one I clicked on to come to the front – big problem.
    I'm really wondering when I do something like
    addChild(sprite) or what ever, what am I adding to it to? I thought
    it was stage, but that isn't it. Evidently after a loooonnggg time
    of trying to understand the help files, I figured out that it was
    the
    [object MainTimeline]
    Whatever that was. And that I could use "this" in my click
    handler because they happened to be the same scope. But I imagine
    at some point they won't be the same. So how do I reference [object
    MainTimeline].
    I guess it is the same issue as AS2 with root and that I
    could use:
    var home=this;
    And then later use:
    home.setChildIndex(event.target,home.numChildren-1);
    Mostly I think typing this up has helped me work out a lot of
    this. But if anybody has any pointers, please share.

    kglad – thanks for that suggestion and I will
    experiment around with it. The strange thing is that if I type home
    as Object the exact line of code (with the event.target not cast as
    anything) works just fine.
    Strangely enough, when I do this:
    setChildIndex(event.target,this.numChildren-1);
    I get the Object coercion error, but if I have home typed as
    an object and do this:
    home.setChildIndex(event.target,this.numChildren-1);
    It works.
    And again the way you have written it, with just
    setChildIndex and nothing in front of that confuses me and brings
    me back to my initial question setChildIndex() of what? How does it
    magically know what scope it should be on. And if I don't need
    anything to scope the setChildIndex, evidently I don't need
    anything to scope the numChildren either so this line works:
    setChildIndex(DisplayObject(event.target),numChildren-1);
    And thanks for that describeType() except it traces a couple
    of pages! And that is what seems to be wrong with AS3, nothing is
    simple! But…wait a minute…that did lead me to
    getQualifiedClassName() which is what I was looking for!

  • AS3: addChild from an AS file

    Hello,
    I have a fla file with a MovieClip named Billy (class: Billy,
    Base Class: flash.display.MovieClip) linked to Billy.as.
    I am trying to get .as file to add an instance of the
    MovieClip Billy onto the stage with no luck. If anybody can help me
    here, Thank You! I am not getting any error messages, just a blank
    swf file...
    this is the code in Billy.as. The fla file is blank.
    package
    import flash.display.MovieClip;
    import Billy;
    public class Billy extends MovieClip
    private var _billy:Billy;
    public function Billy()
    _billy = new Billy();
    addChild(_billy);

    No, it's not tracing.
    package
    import flash.display.MovieClip;
    public dynamic class Billy extends MovieClip
    public function Billy()
    // trace sth just to see it works
    trace("Billy()");
    Also, I learned from a tutorial to name the class.as file as
    the same as the name of the movie clip in the fla file. This was
    from Lynda.com and hasn't caused problems before. I just don't know
    why the class file is not seeing the MovieClip in the fla
    file.

  • AddChild / removeChild variables declaration (when is best?)

    I am putting together my file right now which is now using visual elements purely added and removed via AS3 (addChild / removeChild) methods. My question is just about the proper time / place to declare their variables.
    Can I declare them all at the start of the movie (frame 1) and just call them when I need them, or is it better to declare them on the frames that they are introduced on? I guess the question is really, will I ever lose those variables throughout the movie once they are declared?
    thanks.

    you won't lose variable declarations.  the only thing that could cause a problem was if you referenced an object in a frame where the object doesn't exist.   but you can declare variables to have an object types and do not need to point the variables to objects (until later in your code).

  • (SOLVED!... mostly) Can I load an external image within my custom class?

    Hello there!
    I'm starting to work a lot with Classes, but I'm still reletively new to them.  I wrote a "creature" class (which extends Sprite), and I have everything working nicely... except for when it comes to displaying the image of the creature.
    In previous programs, I've been able to load external Bitmaps using the Loader class.  However, this can only be done from the main timeline in Flash, right?  Such as this:
    var imgLoader:Loader = new Loader();
    imgLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, done);
    imgLoader.load(new URLRequest("001.png"));
    function done(evt:Event):void {
        addChild(Bitmap(imgLoader.content));
    Ideally, what I'd like to do is just have a function within my class.  The function would contain the addChild statement, so I could simply do:
    var MyCreature:creature = new creature();
    MyCreature.loadImage();
    However, I would be equally as happy if I could just load the Bitmap and return it from the class.  Then I could addChild myself in the main timeline:
    var MyCreature:creature = new creature();
    addChild(MyCreature.getBitmap());
    I've tried putting the Loader code in a function within the creature class, however it isn't working.  It didn't return any errors, but it also didn't display anything, despite it containing the addChild statement.  Using the trace command, it looks like its getting inside the function, however addChild doesn't do anything.  Am I missing something?  Is there a better way?
    Here's the function in my creature class:
    public function loadImage(){
         var imgLoader:Loader = new Loader();
         imgLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, done);
         imgLoader.load(new URLRequest("001.png"));
         function done(evt:Event):void {
               trace("It gets to this point just fine");
               addChild(Bitmap(imgLoader.content));
    Thank you!

    Sorry!  Sure enough, I browse the web for hours, unable to find a solution, post a forum post, and then I find a solution.
    http://stackoverflow.com/questions/5036650/as3-addchild-in-a-class
    I simply forgot to add the addChild(MyCreature) in the main timeline.  Duh.  <3

  • Flash CS6; AS3: How to load image from a link on one frame and addChild(image) on other?

    How can I addChild outside the frame of images loader function? When I try to addChild on the other frame of the same loader, I get an error.
    I need to download all my 10 images only ONE TIME and place it on the screen in the other frames (to the same movie Clip).
    Also I can only play this as3 coded frame once. I know how to add an array of images, but I only need to understand how to do it with one image.
    Here is my loader for one image..
       var shirt1 = String("https://static.topsport.lt/sites/all/themes/topsport2/files/images/marskineliai_png/215.pn g");
       var img1Request:URLRequest = new URLRequest(shirt1);
       var img1Loader:Loader = new Loader();
       img1Loader.load(img1Request);
       myMovieClip.removeChildAt(0);
       myMovieClip.addChild(img1Loader);

    Symbol 'Spinner', Layer 'AS', Frame 2, Line 1
    1120: Access of undefined property img1Loader.
    [FRAME1]
    import flash.display.Sprite;
    import flash.events.Event;
    import flash.net.URLLoader;
    import flash.net.URLRequest;
    import flash.events.*;
    import flash.net.URLRequestHeader;
    import flash.net.URLRequestMethod;
    import flash.net.URLVariables;
    import flash.events.SecurityErrorEvent;
    function init(e:Event = null):void
        removeEventListener(Event.ADDED_TO_STAGE, init);
        var loader:URLLoader = new URLLoader();
        var request:URLRequest = new URLRequest("http://www.topsport.lt/front/Odds/affiliate/delfi");
      var acceptHeader:URLRequestHeader = new URLRequestHeader("Accept", "application/json");
      request.requestHeaders.push(acceptHeader);
      request.method = URLRequestMethod.POST;
        //request.url = _jsonPath;
        loader.addEventListener(Event.COMPLETE, onLoaderComplete);
      //loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);
        loader.load(request);
      try {
                    loader.load(request);
                } catch (error:Error) {
                    trace("Unable to load requested document.");
    init();
    function onLoaderComplete(e:Event):void
        var loader:URLLoader = URLLoader(e.target);
        var jsonObject:Object = JSON.parse(loader.data);
      var marsk1 = String("https://static.topsport.lt/sites/all/themes/topsport2/files/images/marskineliai_png/215.pn g");
      var img1Request:URLRequest = new URLRequest(marsk1);
      var img1Loader:Loader = new Loader();
      img1Loader.load(img1Request);
      _2.removeChildAt(0);
      if(_2 != null)
      _2.smoothing = true;
      //    the addChild which works when on frame one
      //_2.addChild(img1Loader);
    [FRAME2]
      _2.addChild(img1Loader);
    p.s. I removed the unnecessary code like other movieClips. It works then addChild function is on frame one.
    I'm kind of new to as3. I started using it this month so sorry if it's the obvious mistake.
    How to make flash recognize the loader?

  • AddChild in AS3 error

    In Flash CS5 I am trying to load an image from a  class and I am getting
    Call to a possibly undefined method addChild.  In the  class file
    Not sure how to fix this as I have a sprite class and believe I have done everthing correct.
    The image is in the same folder as the .fla and .as file
    //class
    package  {
           import flash.display.*;
         public class ClassImg extends Sprite{
              import flash.display.Bitmap;
              import flash.display.Loader;
              import flash.display.Sprite;
              import flash.events.Event;
              import flash.net.URLRequest;
              import flash.text.*;
              public function ClassImg()     {
                   var loader:Loader = new Loader;
              loader.contentLoaderInfo.addEventListener(Event.COMPLETE, imageLoaded);
              loader.load(new URLRequest("ladybug.png"));
              private function imageLoaded(event:Event):void
                   var image:Bitmap = new Bitmap(event.target.content.bitmapData);
                   image.x=10;
                   image.y=10;
                   this.addChild(image); //error is here and I tried just addchild
    //in .fla
    var li:ClassImg= new ClassImg();
    addChild(li);

    yes it works with the import statements in the other area. I must say it took over a day for someone to find the answer to this so well done again.
    q1)Now I am new to this so I believe I need to display an image in a sprite or movie clip container and by extending the class with sprite I am doing this?
    q2) Say I want to make a call to a method in the class which moves the image position to say 200,200.
    How do I set the image to a variable and simply move it?
    The issue is I need an event to tell me the bitmap has loaded so in the fla file I can then be able to move the image.
    PS I dont get that error and I need the sprite and not movie clip. I am using flash CS5 trial. I would like to know why you get this problem

  • HELP! Uploading AS3 Game to server, no sound and Spacebar doesn´t work HELP!

    Hello, relatively new to AS3 and flash, this is the first time i am publishing anything. We are trying to upload our simple flashgame to our webserver, the game works perfectly fine locally save for one thing. We get an error regarding TLF which says it wont stream or something. So when it gets online, no sounds play and spacebar doesn't work, left and right arrow does work. We have three TLF text fields that are used to update score, lives and show you final score. If i turn these into classical text they stop working.
    Things we have tried: Changing default linkage from RLS to Merged into code, changing the text boxes to classical text(they then stop working), made sure the paths are correct(all files are in the same directory including the .swz file)
    This is the code from the soundclass:
    package 
        import flash.net.URLRequest;
        import flash.media.Sound;
        import flash.media.SoundChannel;
        import flash.events.*;
        public class MySound
            private var bgSound:Sound;
            private var fireSound:Sound;
            private var waterSound:Sound;
            private var earthSound:Sound;
            private var lightSound:Sound;
            private var soundChannel:SoundChannel;
            public function MySound()
                soundChannel = new SoundChannel();
                bgSound = new Sound();
                var req:URLRequest = new URLRequest("BackgroundSound.mp3");
                bgSound.load(req);
                //fire
                fireSound = new Sound();
                var req2:URLRequest = new URLRequest("soundFire.mp3");
                fireSound.load(req2);
                // water
                waterSound = new Sound();
                var req3:URLRequest = new URLRequest("soundWater.mp3");
                waterSound.load(req3);
                // earth
                earthSound = new Sound();
                var req4:URLRequest = new URLRequest("soundEarth.mp3");
                earthSound.load(req4);
                // light
                lightSound = new Sound();
                var req5:URLRequest = new URLRequest("soundLight.mp3");
                lightSound.load(req5);
            public function playBgSound()
                soundChannel = bgSound.play(0, 999999);
            public function stopBgSound()
                soundChannel.stop();
            public function playFireSound()
                fireSound.play();
            public function playWaterSound()
                waterSound.play();
            public function playEarthSound()
                earthSound.play();
            public function playLightSound()
                lightSound.play();
    I can somewhat get that sound can bugg out, but why does spacebar stop functioning? ANy help is greatly appreciated as this has to be delivered in twelve hours(published online) for a school assignment.

    Also might add publishing it locally in my own browser everything works, as does ofcourse playing it in flash itself. Changing from RLS to merged into code stops the error from coming, but doesn´t fix the problem on the server.
    Code from main class related to sound and spacebar:
    import flash.display.*;
        import flash.events.*;
        import flash.ui.Keyboard;
        import flash.text.TextField;
        import flash.media.Sound;
        import flash.net.URLRequest;
        import flash.events.MouseEvent;
        import flash.utils.Timer;
        import flash.events.TimerEvent;
        public class main extends MovieClip
            private var fireTimer:Timer; //delay between shots
            private var canFire:Boolean = true;
            private var mySound:MySound;
            private var bulletSpeed:Number = -450;
              public function main()
                //load sounds
                mySound = new MySound();
            private function playGame(event:MouseEvent)
                gotoAndStop(2);
                // initialize
                myLives = 5;
                myHitsNo = 0;
                weaponType = 1;
                mybullets = new Array();
                enemys = new Array();       
                myScoreTxt.text = "Score: " + myHitsNo;
                myLivesTxt.text = "Lives: " + myLives;   
                fireTimer = new Timer(400, 1);
                fireTimer.addEventListener(TimerEvent.TIMER, shootTimerHandler, false, 0, true);
                stage.addEventListener(KeyboardEvent.KEY_DOWN, listenKeyDown);
                stage.addEventListener(Event.ENTER_FRAME, addEnemy);
                stage.addEventListener(Event.ENTER_FRAME, checkCollision);   
                player = new thePlayer(stage.stageWidth-40, spawnPoint2);// stage.stageHeight/2);
                stage.focus = player;
                addChild(player);
                mySound.playBgSound();
    public function listenKeyDown(event:KeyboardEvent)  // Controls and weapontype selector
                if (event.keyCode == 37) //left
                    player.movethePlayerDown();
                if (event.keyCode == 39) //right
                    player.movethePlayerUp();
    if (event.keyCode == Keyboard.SPACE) //space
                    shootBullet();
                    //soundFX.attachSound("Pistol Fire.wav");
                    //soundFX.start();

  • AS3 Scripting for Animated GIF

    Hi,
    I am trying to create an animated GIF for a white noise animation (needed for those viewers who don't have access to a Flash player). The SWF version runs perfectly. Currently, all of the AS3 for the bitmapData.noise and bitmapData.palettemap script is in the first keyframe. So, when I export as an animated GIF, I get a white screen in playback.
    I think the problem for the animated GIF is that there are no frames past the first frame. But, I am not sure how to add frames or re-write the AS3 to get a 30 second animated GIF? I tried duplicating the first keyframe into several new keyframes and get error messages. I would appreciate any help.
    Here's the AS3 in the first keyframe that works well for a SWF (previous relevant thread: http://forums.adobe.com/thread/734335?tstart=0):
    var array:Array=new Array();
    for (var i:uint = 0; i < 255; i++) {
    array[i] = 0xffffff * (i % 2);
    var _bitmapData:BitmapData;
    var bDHolder:Sprite = new Sprite();
    _bitmapData = new BitmapData(stage.stageWidth/4, stage.stageHeight/4);
    bDHolder.addChild(new Bitmap(_bitmapData));
    bDHolder.scaleX = bDHolder.scaleY = 4;
    addChild(bDHolder);
    addEventListener(Event.ENTER_FRAME, onSpriteEnterFrame);
    function makeNoise():void {
                _bitmapData.noise(getTimer(), 100, 255, 7, true);
                _bitmapData.paletteMap(_bitmapData, _bitmapData.rect, new Point(0,0), array, array,array);
    function onSpriteEnterFrame(event:Event):void {
                makeNoise();
    var itsNoisy:Boolean = true;
    stage.addEventListener(MouseEvent.MOUSE_DOWN, manageNoise);
    function manageNoise(evt:MouseEvent):void {
         if(itsNoisy){
             removeEventListener(Event.ENTER_FRAME, onSpriteEnterFrame)
         } else {
             addEventListener(Event.ENTER_FRAME, onSpriteEnterFrame)
         itsNoisy = !itsNoisy;
    Kind Regards,

    Jimmy,
    You may (also) try to ask in the (most) relevant Photoshop forum.
    http://forums.adobe.com/community/photoshop

  • How can I display a Movie clip from library on stage in AS3?

    Hi,
    I have a movie clip in my library and I would like to display it on the stage using AS3.
    do I have to define it as a variable?Do  I need to use this code:  addchild(movieclip);
    can I use the 'x' and 'y' to position it?
    What would the code look like?
    Ben.

    Great! it works  well ! thanks
    But I have another question, if I wanted to used the same movie clip but postion it at different x and y positions when a different btn is selected how could I do that?
    Would I have to make a copy of the movie clip and give it a different name?
    or is there an better way around it?
    Ben.

  • How do I get external classes to work in AS3? Sample included.

    I'm trying to make this work, and something basic must be missing.  Its straight out of the Adobe help file example.
    CS4, Actionscript 3
    Here's what I'm doing:
    1.  create an .as file and name it "HelloWorldExample"
    2.  Put the script below in it and save it.
    3.create a new .fla file and save it to the same directory.
    4.in that .fla file, put "HelloWorldExample" in the Document properties Class field
    5. Save it and run the movie.
    I get a white screen.  Nothing.  I've tried a few other examples as well, but I haven't been able to get ANY external .as files to run. This is the simplest one.
    Do I need to import them or call them in some way other than step 4?
    Did I miss something?
    package
        import flash.text.engine.*;
        import flash.display.Sprite;
        public class HelloWorldExample extends Sprite
            public function HelloWorldExample()
                var str = "Hello World! This is Flash Text Engine!";
                var format:ElementFormat = new ElementFormat();
                var textElement:TextElement = new TextElement(str, format);
                var textBlock:TextBlock = new TextBlock();
                textBlock.content = textElement;
                var textLine1:TextLine = textBlock.createTextLine(null, 300);
                addChild(textLine1);
                textLine1.x = 30;
                textLine1.y = 30;

    As long as you have your class paths set properly, it's better to have your .as files located in a different loc than your .fla. What if you want to use the same class in different .fla files? Are you going to copy it into every project folder? That sort of defeats the purpose of using classes then, because if you change it you have to change it in various places. Not good. Not OOD.
    So: Edit > Preferences > AS3 Settings - Add paths to the source path... or one path... something like c:\flashclasses\as3
    Then inside your as3 folder you set your package folders. If you use TweenLite you'd have:
    com
         greensock
              TweenLite classes
    or your own:
    com
         myDomain
              my classes
    then you'd import like:
    import com.greensock.TweenLite;
    import com.myDomain.myClass;
    Make sense?

  • [AS3 AIR] 2880x2880 Size Limit, Camera, Filter, CameraRoll Issues & Finger Friendly Components

    AS3 AIR ANDROID
    I started playing with this Adobe AIR for Adroid by building an app that would let the user take a picture using the mobile device's native camera app.  Then, I'm applying filter effects to make the image look cool.  Then, I'm allowing the user to save the image back to the camera roll.
    Here are some questions that I have:
    KEEPING UP WITH CURRENT TECHNOLOGY
    Are we limited to the 2880x2880 stage size limit?  Although, this dimension does yield 8+megapixels, it's not in the ratio that most camera sensors are built (widescreen).  Plus, you can bet that newer cameras will have even higher dimensions.  Will this be updated to keep up with current technology requirements?
    IMPORTING & MANIPULATING CAMERA DATA
    Code
    var bmpData:BitmapData = new BitmapData($loader.width, $loader.height);
    bmpData.draw(DisplayObject($loader));
    bmp = new Bitmap(bmpData);
    bmp.width = Capabilities.screenResolutionX;
    bmp.height = Capabilities.screenResolutionY;
    if (CameraRoll.supportsAddBitmapData) {
        var cameraRoll:CameraRoll = new CameraRoll();              
        cameraRoll.addEventListener(ErrorEvent.ERROR, onCrError);
        cameraRoll.addEventListener(Event.COMPLETE, onCrComplete);
        var savedBmpData:BitmapData = new BitmapData (bmp.width, bmp.height);
        savedBmpData.draw(DisplayObject(bmp));
        cameraRoll.addBitmapData(savedBmpData);
    } else {
        trace("~" + "Camera Roll not supported for this device.");
    addChild(bmp);
    When you capture an image using the mobile device's camera app, you have to use the Loader object.
    So, here, I am doing just that with these steps:
    First, I'm creating a BitmapData object and sizing it the same as the camera image.
    Pass the camera image into the BitmapData object.
    Create a Bitmap object and pass in the BitmapData.
    Resize it to fit on the stage.
    Check for Camera Roll and then create a savedBmpData BitmapData object at the size of the screen.
    Pass in the bmp.
    Save it to the Camera Roll.
    The problem is that when the image is displayed on the phone, it shows THE ENTIRE (uncropped) image.  However, the image that is saved to the phone is only the top 800x480 corner of the image.  What is wrong?  How do we save an image to the Camera Roll that is larger than the display area of the phone.  It seems like the only way to save the entire camera image is to resize it to fit the stage and then capture the stage into a bitmapData object.
    FILTERS
    If you apply any filters to the bitmapData object, the filter effects will display on the phone, but if the image is saved to the Camera Roll, then all the filters are lost and it only saves the original (unfiltered) image.
    FINGER FRIENDLY UI COMPONENTS
    Do they exist?
    ADDITIONAL NOTES
    The max image size that can be saved is 2039x2039 pixels on the HTC Evo.  Anything bigger than this resulted in a CameraRoll Error #1 (which there is no documentation for what that means ANYWHERE on the web).

  • How to use a flex custom component in an AS3 Class?

    Our software team has been developing flash applications using AS3 (via the FlashDevelop IDE and the free Flex SDK).  Recently, some members of the team started exploring FlexBuilder and Flex (wow... why did we wait so long?).  The problem is that some folks continue to develop using pure Action Script 3 (FlashDevelop) while others are creating custom components in FlexBuilder.
    How do the AS3 developers use the Flex Custom components built in FlexBuilder in their AS3 Applications?

    SwapnilVJ,
    Your suggestions enabled me to make progress, but I'm still having a problem.  Based on you suggestion, I learned how to make a swc using Flex Builder.  I successfully added the swc to the lib resource in my AS3 project (FlashDevelop).  I was able to instantiate one of my new components (code hinting even picked it up from the lib).
    When I run my app, my component is not visible.  I can trace properties of it and the values are correct.  Any thought why I might not be seeing my custom component?
    package trainer.games.board.MatchThree {
    import flash.display.Sprite;
    public class Test extends Sprite{
      private var cp:MatchingGameControlPanel; // <<< this is my swc custom component created in Flex
      public function Test() {
       cp = new MatchingGameControlPanel();
       cp.visible = true;
       addChild(cp);
       trace("width: ",cp.width); // <<< works and displays valid data for the component.

  • Need to get rid of persistent images created with as3 - pls help

    I have used the following as3 code, courtesy of Jody Hall at theflashconnection.com .  It's a drag and drop that works great. Problem is the drag and drop images persist when I move on to other frames. How do I clear the images when finished so they don't appear in subsequent frames? Thank you in advance.
    import flash.events.MouseEvent;
    import flash.display.MovieClip;
    import flash.media.Sound;
    import flash.media.SoundChannel;
    var sndExplode:explode_sound;
    var sndExplodeChannel:SoundChannel;
    var dragArray:Array = [host1, agent1, physical1, social1, host2, agent2, physical2, social2, host3, agent3, physical3, social3];
    var matchArray:Array = [targethost1, targetagent1, targetphysical1, targetsocial1, targethost2, targetagent2, targetphysical2, targetsocial2, targethost3, targetagent3, targetphysical3, targetsocial3];
    var currentClip:MovieClip;
    var startX:Number;
    var startY:Number;
    for(var i:int = 0; i < dragArray.length; i++) {
        dragArray[i].buttonMode = true;
        dragArray[i].addEventListener(MouseEvent.MOUSE_DOWN, item_onMouseDown);
        matchArray[i].alpha = 0.2;
    function item_onMouseDown(event:MouseEvent):void {
        currentClip = MovieClip(event.currentTarget);
        startX = currentClip.x;
        startY = currentClip.y;
        addChild(currentClip); //bring to the front
        currentClip.startDrag();
        stage.addEventListener(MouseEvent.MOUSE_UP, stage_onMouseUp);
    function stage_onMouseUp(event:MouseEvent):void {
        stage.removeEventListener(MouseEvent.MOUSE_UP, stage_onMouseUp);
        currentClip.stopDrag();
        var index:int = dragArray.indexOf(currentClip);
        var matchClip:MovieClip = MovieClip(matchArray[index]);
        if(matchClip.hitTestPoint(currentClip.x, currentClip.y, true)) {
            //a match was made! position the clip on the matching clip:
            currentClip.x = matchClip.x;
            currentClip.y = matchClip.y;
            //make it not draggable anymore:
            currentClip.removeEventListener(MouseEvent.MOUSE_DOWN, item_onMouseDown);
            currentClip.buttonMode = false;
            sndExplode=new explode_sound();
            sndExplodeChannel=sndExplode.play();
        } else {
            //match was not made, so send the clip back where it started:
            currentClip.x = startX;
            currentClip.y = startY;
    DRAG AND DROP (I JUST DID THE LAST FOUR FOR THIS EXAMPLE)
    MOVING ON TO NEXT FRAME, YOU STILL SEE THE RECTANGLES.

    Thank you SO muchNed Murphy
    I'm a newbie to AS3 and I was trying to figure it out for past 2 weeks that why did swapChildren or setChildIndex or addChild, all of these made my Target Movieclip remain/duplicate/persist on the stage even after the layer containing the Target Movieclip has blank keyframes. I surfed so many forums and tutorials for the answer but turns out it was my lack of knowledge of basic concepts. I remember checking out this specific forum as well past week but due to it being "Not Answered" I skipped it. This should be marked as a "Correct Answer", The Empty MovieClip did the trick!
    I needed this solution for a Drag and Drop game, so that the current item that is being dragged is above all other graphic layers. And when all items are dropped on their correct targets, there is gotoAndPlay to Success frame label.
    I created a movieclip on the top layer with the same dimensions as the stage and put it at x=0 y=0 position. Instance name: emptymc
    And deleted the emptymc from the timeline during the Success frame label.
    Here is some code I used,
    1. MovieClip.prototype.bringToFront = function():void {
       emptymc.addChild(this);
    2.  function startDragging(event:MouseEvent):void {
      event.currentTarget.startDrag();
      event.currentTarget.bringToFront();
    I didn't know how to put the addChild and refer to the currentTarget in the startDragging function itself, for example
    emptymc.addChild(event.currentTarget);
    - This one didn't work inside the startDragging function "emptymc.addChild(this); "
    Is there a correct way I could have done it properly?
    Thanks,
    Dipak.

  • Publishing a flash with AS3.0 on website does not work

    Okay, I'm finally at the end of my flash card. Here's the whole code.
    //import classes
    import com.greensock.TweenLite;
    import com.greensock.easing.*;
    import fl.transitions.Tween;
    import fl.transitions.easing.*;
    //end of importing
    //start of sound section is for sound
    var cssLoader:URLLoader;
    var css:StyleSheet;
    var soundReq:URLRequest=new URLRequest("audioFiles/PaukenBrumfiel_AngelsOnHigh.mp3");
    var sound:Sound = new Sound();
    sound.load(soundReq);
    sound.addEventListener(Event.COMPLETE, onComplete);
    //end of sound section
    //Loading external texts
    var weiss:Font = new Weiss();
    var weissBold:Font = new WeissBolder18();
    var weissBolder:Font = new WeissBolder();
    var slideXTween:Tween;
    var txtAlphaTween:Tween;
    var txtNextText:Tween;
    var txtContainer:Sprite;
    var txtField:TextField = new TextField();
    var myTxtField:TextField = new TextField();
    var txtFldwebImages:TextField = new TextField();
    var textRequest:URLRequest=new URLRequest("happyHoliday.txt");
    var textLoad:URLLoader = new URLLoader();
    var txtFormat:TextFormat = new TextFormat();
    var myLinkFormat:TextFormat = new TextFormat();
    var strLink:String;
    var numXPos:Number;
    var numYPos:Number;
    //end of loading external texts
    function onComplete(event:Event):void {
        sound.play();
    function textReady(event:Event):void {
        //txtFormat.font= weiss.fontName;
        txtFormat.color=0x000066;
        txtFormat.size=24;
        //txtField.x = stage.stageWidth;
        //txtField.width = 800;
        txtField.autoSize=TextFieldAutoSize.LEFT;
        //txtField.height = txtField.autoSize
        txtField.wordWrap=false;
        txtField.text=event.target.data;
        txtField.setTextFormat(txtFormat);
        //txtField.y = 350;
        txtField.embedFonts=true;
    textLoad.load(textRequest);
    txtFormat.font= weiss.fontName;
    textLoad.addEventListener(Event.COMPLETE, textReady);
    txtField.x=stage.stageWidth;
    addChild(txtField);
    txtField.y=350;
    TweenLite.to(txtField, 40, {x:-stage.stageWidth*2.25, ease:Linear.easeNone, delay:0.5, onComplete:Inspiration});
    function Inspiration():void {
        txtFormat.font= weissBolder.fontName;
        textLoad.load(new URLRequest("inspiration.txt"));
        txtField.x=130;
        txtField.y=330;
        txtField.alpha=0;
        TweenLite.to(txtField, 5, {alpha:1, onComplete:GoogleFunc});
    function GoogleFunc():void {
        //create and initialize css
        addChild(myTxtField);
        strLink = "<a href='http://www.google.com/' target='_blank'>Google</a>";
        numXPos = 180;
        numYPos = 370;
        var myCSS:StyleSheet = new StyleSheet();
        myCSS.setStyle("a:link", {color:'#000066',textDecoration:'none'});
        myCSS.setStyle("a:hover", {color:'#FF6600',textDecoration:'underline'});
        txtFormat.font = weissBold.fontName;
        //txtFormat.color=0x000066;
        txtFormat.size=20;
        //txtFormat.bold = true;
        myTxtField.setTextFormat(txtFormat);
        myTxtField.defaultTextFormat=txtFormat;
        myTxtField.styleSheet = myCSS; // Linking CSS to TextField
        myTxtField.htmlText="";
        myTxtField.htmlText=strLink;
        myTxtField.wordWrap=false;
        //myTxtField.embedFonts = true;
        myTxtField.width = strLink.length*2;
        myTxtField.x=numXPos;
        myTxtField.y=numYPos;
        //trace("Third txtField.y: " + txtField.y);
        myTxtField.alpha=0;
        TweenLite.to(myTxtField, 1, {alpha:1, onComplete:webImages});
        //trace("tween done");
    function webImages():void {
        addChild(txtFldwebImages);
        var myCSS:StyleSheet = new StyleSheet();
        myCSS.setStyle("a:link", {fontsize:'20',color:'#000066',textDecoration:'none'});
        myCSS.setStyle("a:hover", {fontsize:'20',color:'#FF6600',textDecoration:'underline'});
        txtFormat.font = weissBold.fontName;
        //txtFormat.color=0x000066;
        txtFormat.size=20;
        //txtFormat.bold = true;
        txtFldwebImages.setTextFormat(txtFormat);
        txtFldwebImages.defaultTextFormat=txtFormat;
        txtFldwebImages.styleSheet = myCSS; // Linking CSS to TextField
        txtFldwebImages.htmlText = "";
        txtFldwebImages.htmlText="<a href='http://www.google.com/webImages/' target='_blank'>Google Images</a>";
        txtFldwebImages.wordWrap=false;
        //myTxtField.embedFonts = true;
        txtFldwebImages.width = 300;
        txtFldwebImages.x=300;
        txtFldwebImages.y=370;
        txtFldwebImages.alpha=0;
        TweenLite.to(txtFldwebImages, 1, {alpha:1});
    //end of loading external texts
    Okay, the problem is when I publish the .swf files and put it in an html or .aspx page, it does not work. The audio is not there and a few others things ar enot working. However, it does work if I click on the.html file that Flash created during the publication.
    Here are the folder structions:
    www.mysite.com/myFlashPage.aspx
    www.mysite.com/flashFileFolder/
    www.mysite.com/flashFileFolder/audioFiles/
    So, the myFlashPage.aspx containsthe myFlash.swf file that is inside the flashFileFolder. For some reason, it does not work. Any suggestion is much appreciated.

    The .html file does work if I publish it into the same folder as I created the Flash project. However, when I publish the
    flash .swf to my web site folder (mapped), it's no longer working. The mapped web site drive structher are as follows:
    D:\Mysite\ contains the .html file
    D:\Mysite\flashFileFolder\ contains the .swf file
    D:\Mysite\flashFileFolder\audioFiles contains the PaukenBrumfiel_AngelsOnHigh.mp3 file
    D:\Mysite\flashFileFolder\greensock-tweening-platform-as3 contains all the tweenlite files
    The .html file does not work either. What else do I need to change?

Maybe you are looking for

  • Is there an "Edit Object Tool" in Acrobat 11?

    Is there an "Edit Object Tool" in Acrobat 11 that is comparable to the Edit Object Tool in Acrobat 10 and earlier versions?  Has it been discontinued, or split into 2 loosely connected tools, the new Edit Text and Images Tool? I love the new Edit Tex

  • How to I get the iPad to recognize a number beginning with 0 without it cutting off the 0

    How do I get the iPad to recognize a number beginning with 0 without dropping the 0.  And how do I get the iPad to recognize a 4 (birth year) or 5 (zip code) digit number with adding a comma delineating it to thousands?

  • AIR unknown publisher..

    Check this pic. anyone know hwo to replace UNKNOWN" with my name? I check ***-app.xml ,but cant find how to change. and alose the system access. thanks

  • How do I save my edited I/O Labels ?

    Hi, I am setting up Logic X and 99% good so far. However I have updated all the I/O Labels in the mixer view and when I leave Logic and go back in again.... they are gone !!  Can someone tell me how to save them as default for all Logic songs. Thanks

  • Adobe Reader x (10.1.3)

    I am trying to uninstall Adobe Reader X(10.1.3). I am getting a message that says this patch package could not be opened. Verify the patch package exist and you can access it, or contact the application vendor to verify it is a valid Windows Installe