Reputation: 1296
As the title shows, I have 2 container MovieClips (mc1, mc2), each of them has a separate x,y, rotation. I want to take a child from mc1 and addChild() it to mc2 while keeping the same x, y, and rotation on the screen so you see the added child mc as if it didnt change position or rotation, just moved to the other MC. Any idea how?
Upvotes: 0
Views: 1280
Reputation: 1768
If you got deeply nested transforms I'd use something like this. For example you have nested sprites mc1.mc2.mc3
and you want to reattach mc3
to mc4
. This one looks how much the right vector (1, 0) in one coordinate system differs from same vector in another one.
function reattach(target:DisplayObject, to:DisplayObjectContainer):void {
var center:Point = target.localToGlobal(new Point(0,0));
// vector (1, 0) from old local coordinate system
var oldVector:Point = target.localToGlobal(new Point(1,0)).subtract(center);
var newCenter:Point = to.globalToLocal(center);
to.addChild(target);
target.x = newCenter.x;
target.y = newCenter.y;
// vector (1, 0) from new local coordinate system
var newVector:Point = target.localToGlobal(new Point(1,0)).subtract(center);
// angle between these two vectors
var angle:Number = Math.acos((oldVector.x*newVector.x + oldVector.y*newVector.y)/(oldVector.length*newVector.length)) * 180 / Math.PI;
if (oldVector.x*newVector.y - oldVector.y*newVector.x > 0) angle = -angle;
// rotating for delta angle
target.rotation += angle;
}
reattach(mc1.mc2.mc3, mc4);
Have to be modified if any of the sprites are scaled
Upvotes: 0
Reputation: 27506
You can use localToGlobal()
and globalToLocal()
to achieve that.
var positionInMc1:Point = new Point(child.x, child.y);
var positionInStage:Point = mc1.localToGlobal(positionInMc1);
var positionInMc2:Point = mc2.globalToLocal(positionInStage);
mc2.addChild(child);
mc2.x = positionInMc2.x;
mc2.y = positionInMc2.y;
Edit:
However, this will not handle the rotation correctly. So you will probably have to rotate child
after that to correct for the rotation of mc1
and mc2
. As they are in the same level, you should probably rotate child
by the difference between their respective rotations.
Edit:
From the code you posted below:
child.rotation -= mc2.rotation;
Upvotes: 1
Reputation: 7722
Maybe this piece of code might help you out: You can specify a point which you want to translate into the coordinate system of another movie clip.
public static function localToLocal(from:Sprite, to:Sprite, origin:Point):Object
{
var point:Point = new Point(origin.x,origin.y);
point = from.localToGlobal(point);
point = to.globalToLocal(point);
return point;
}
The problem remains, if there are multiple sub-movieclips, that are rotated individually. Otherwise you can use just the one rotation you have applied to the movieclip, and apply it to a new wrapper-clip.
Upvotes: 1