views:

35

answers:

2

I have 2 object. In different depths of MovieClip. I would like to know if object A parent is same with object B parent. I wanted to dynamically add '.parent' to object A/B till it both reaches the same level (having the same parent object). How can I do that?

My idea was to have something like

objectA = objectA + ".parent"

and make it loop till it reaches the target. But this is not the correct way to add in more layers of '.parent'. Anyone know how it should be coded?

A: 
var mc:MovieClip;
while (mc.parent != null && mc.parent != targetParent)
{
    mc = mc.parent;
}
alxx
Using `DisplayObjectContainer` instead of `MovieClip` would be a better choice, if not the loop may fail.
grapefrukt
+1  A: 

You can use contains method

public function contains(child:DisplayObject):Boolean
Determines whether the specified display object is a child of the DisplayObjectContainer instance or the instance itself. The search includes the entire display list including this DisplayObjectContainer instance, grandchildren, great-grandchildren, and so on.

function haveCommonParent(a:DisplayObject, b:DisplayObject):Boolean
{
  for(var p:DisplayObjectContainer = a.parent; p != null; p = p.parent)
  {
      if(p.contains(b))
          return true;
  }
  return false;
}

Might be slow for huge display lists.

Update: get the common parent, if any. This will return a Stage object if both are on stage.

function getCommonParent(a:DisplayObject, b:DisplayObject):DisplayObjectContainer
{
  for(var p:DisplayObjectContainer = a.parent; p != null; p = p.parent)
  {
      if(p.contains(b))
          return p;
  }
  return null;
}
Amarghosh
May be better to return the common parent, or `null` if there is none. As it is, this will return `true` most of the time, as all objects in a scene typically share the stage as a common ancestor.
Gunslinger47
@Gunslinger Good point. Updated.
Amarghosh