Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AS3 - How to find the position of an object relative to the stage?

If I have a rectangle on the stage, how do I find its top left tip (x,y) and the bottom right tip (x,y) in relation to the stage? It strange how I can't find this on google!

like image 595
muudles Avatar asked May 17 '11 07:05

muudles


4 Answers

localToGlobal(point) of DisplayObject Converts the point object from the display object's (local) coordinates to the Stage (global) coordinates.

// assuming (0, 0) is top left
var topLeftStage:Point = myDisplayObject.localToGlobal(new Point(0, 0));

// bottom right
var bottomRightStage:Point = myDisplayObject.localToGlobal(new Point(width, height));
like image 196
taskinoor Avatar answered Nov 28 '22 20:11

taskinoor


You can do this in one line, e.g. if the container you've added it to is a DisplayObject as well, you can write:

var rect:Rectangle = yourDisplayObject.getBounds(stage);

That will jump directly to getting you a rectangle relative to the stage. You can then access the values you mentioned specifically:

rect.bottomRight
rect.topLeft
like image 32
Michael Martin Avatar answered Nov 28 '22 18:11

Michael Martin


If your object is in one container then you can just subtract the containers's position from the objects's position.

var rawx:Number = x - parent.x;
var rawy:Number = y - parent.y;

Else use localToGlobal() like above.


Finding the top left and bottom right points of an object is easy - but you need to know where the registration point of the symbol is.

If the registration point where in the centre of the symbol:

var left:Number = x - (width / 2);
var right:Number = x + (width / 2);
var top:Number = y - (height / 2);
var bottom:Number = y + (height / 2);

If it were at the top left:

var left:Number = x;
var right:Number = x + width;
var top:Number = y;
var bottom:Number = y + height;

Etc.

like image 41
Marty Avatar answered Nov 28 '22 20:11

Marty


if the displayobject does not start at 0,0 of the movieclip, you'll need this:

var skin:DisplayObject = ... //the MC you need to get positions of
var point : Point = skin.localToGlobal(new Point(skin.getBounds(skin).x,skin.getBounds(skin).y));
var point2 : Point = skin.localToGlobal(new Point(skin.getBounds(skin).x+skin.getBounds(skin).width,skin.getBounds(skin).y+skin.getBounds(skin).height));

and the results will be:

x=point.x;
y=point.y;
width=point2.x-point.x;
heigth=point2.y-point.y;
like image 25
csomakk Avatar answered Nov 28 '22 18:11

csomakk