views:

11656

answers:

5

How do you get/set the absolute position of a MovieClip in Flash/AS3? And by absolute, I mean its position relative to the stage's origo.

I currently have this setter:

class MyMovieClip extends MovieClip
{
  function set xAbs(var x:Number):void
  {
    this.x = -(this.parent.localToGlobal(new Point()).x) + x;
  } 
}

This seems to work, but I have a feeling it requires that the Stage is left aligned.

However, I don't have a working getter. This doesn't work:

public function get xAbs():Number 
{
  return -(this.parent.localToGlobal(new Point()).x) + this.x; // Doesn't work
}

I'm aiming for a solution that works, and works with all Stage alignments, but it's tricky. I'm using this on a Stage which is relative to the browser's window size.

EDIT: This works for a top-left aligned stage; not sure about others:

public function get AbsX():Number 
{
    return this.localToGlobal(new Point(0, 0)).x;
}    
public function get AbsY():Number 
{
    return this.localToGlobal(new Point(0, 0)).y;
}    
public function set AbsX(x:Number):void
{
    this.x = x - this.parent.localToGlobal(new Point(0, 0)).x;
}
public function set AbsY(y:Number):void
{
    this.y = y - this.parent.localToGlobal(new Point(0, 0)).y;
}
+2  A: 

Two things:

Why the substractions?

var x=this.parent.localToGlobal(new Point(this.x,0)).x;

should give the proper result already. If the parent clip is scaled, your calculation will be off by the scaling factor...

Just a shot in the dark, but you could add a globalToLocal(this.stage) for compensating the alignment issues?

moritzstefaner
What about the setter?
bzlm
+1  A: 

Agree with moritzstefaner that you don't need the subtraction stage, however for your setter I actually think you should use globalToLocal, and use localToGlobal for your getter. These will take care of scaling and rotation as well as position.

Iain
Could you provide an example in code?
bzlm
A: 

i couldnt use localToGlobal so as an alternative solution is to get the position of the mouse in the scope you want :

mynestesprite.addEventListener (MouseEvent.MOUSE_OVER, myover)
function myover(e:MouseEvent){
    // e.target.parent.parent ....
     trace ( e.target.parent.parent.mouseX, e.target.parent.parent.mouseY)
}
+1  A: 

THANK YOU SO MUCH!!!!

TO GET POSITION OF OBJECT RELATVE TO STAGE USE:

  • (object as DisplayObject).localToGlobal(new Point()).x;
  • (object as DisplayObject).localToGlobal(new Point()).y;
asdfasdf
thanks, also works for flex 4
ufk
A: 

I have a question: I am working on a flash tool which has selectable movie clips which then populate an area of the form. As new movie clips are selected they are added above the previous on. I need help with positioning the list movie clips on top of each other. The order to select the movie clips will vary as well.

Thanks.

BeGaget