Flash/AS3; get/set absolute position of MovieClip?

41,034

Solution 1

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?

Solution 2

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;

Solution 3

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.

Share:
41,034
user772401
Author by

user772401

hej

Updated on October 17, 2020

Comments

  • user772401
    user772401 over 3 years

    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;
    }