R – How to remove child(Movieclip) and add to new parent (Movieclip)

actionscript-3flash

I need to remove the child(movieClip) from the parent(movieClip) while dragging and add the same child(movieClip) to another movieclip when dropped.

this method is used for dragging

function pickUp(event:MouseEvent):void 
{
    event.target.startDrag();
}

when i drop it

function dropIt(event:MouseEvent):void
{
    event.target.parent.removeChild(event.target); //for removing from previous parent clip

    event.target.dropTarget.parent.addChild(event.target); // add to new Moviclip
}

But the clip is not visible or not available while dropping…

Help me to overcome from this Problem.

Best Answer

I had a quick play, here is what I came up with:

My example has a MovieClip on the stage called "ball", and a number of other MovieClip scattered around for use as dropTargets.

ball.addEventListener(MouseEvent.MOUSE_DOWN, pickUp);
stage.addEventListener(MouseEvent.MOUSE_UP, dropIt);

function pickUp(event:MouseEvent):void 
{
    var ballPoint:Point = ball.parent.localToGlobal( new Point(ball.x, ball.y) );

    ball.parent.removeChild(ball);
    addChild(ball);
    ball.x = ballPoint.x;
    ball.y = ballPoint.y;
    ball.startDrag();
}

function dropIt(event:MouseEvent):void 
{
    ball.stopDrag();
    if(!event.target.dropTarget) { return };

    var dropT:MovieClip = event.target.dropTarget.parent;
    var ballPoint:Point = dropT.globalToLocal( new Point(ball.x, ball.y) );

    ball.parent.removeChild(ball);
    dropT.addChild(ball);
    ball.x = ballPoint.x;
    ball.y = ballPoint.y;
}

Basically, the PickUp handler removes the "ball" MovieClip from its parent, and adds it to the root DisplayObject. This makes sure the ball is on top, so the dropTarget will work (dropTarget will only work with Objects lower in the stack order). The ball's x/y position is calculated (using localToGlobal) for its new parent, and applied. Then start drag is called.

The dropIt handler first calls stopDrag, then returns if it can't find a dropTarget. A new x/y position for the ball is calculated using globalToLocal this time, to get its new position in its droptarget. The ball is then removed and added to its new parent (the dropTarget). The new position is applied.

Seems to work really well in my case.

Also... I found that a good way to test if it's working, is to temporarily apply different blur or dropShadow filters to the dropTargets on the stage. That way when you drop the ball onto them, it will inherit the filter, and you can see some visual feedback.

Related Topic