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

笑着哭i 提交于 2019-12-21 03:49:38

问题


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!


回答1:


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



回答2:


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



回答3:


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.




回答4:


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;


来源:https://stackoverflow.com/questions/6027408/as3-how-to-find-the-position-of-an-object-relative-to-the-stage

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!