获得从原点到左上角的相对距离

时间:2013-10-02 10:57:28

标签: actionscript-3 flash sprite

下面是一张解释我所拥有的图片:
Describing image

棕色方块是我添加的Sprite的本地原点。 (我 无法更改图形!)

如何获得Flash AS3中两点之间的X和Y距离? 或者我如何以编程方式将原点移动到左上角?

1 个答案:

答案 0 :(得分:1)

只需使用getBounds(),它就包含您所需要的一切。

一个例子:

package
{
    import flash.display.DisplayObject;
    import flash.display.Sprite;
    import flash.events.MouseEvent;
    import flash.geom.Point;

    public class TestSquare extends Sprite
    {
        public function TestSquare()
        {
            var squareMc : Sprite = new Sprite;

            squareMc.graphics.lineStyle(5);
            squareMc.graphics.beginFill(0xFFAAAA);
            squareMc.graphics.drawRect(-20,-20,100,100);
            squareMc.graphics.endFill();
            addChild(squareMc);

            squareMc.addEventListener(MouseEvent.CLICK, onClick);
        }

        protected function onClick(event:MouseEvent):void
        {
            // Cancel offset
            var squareMc : DisplayObject = event.target as DisplayObject;
            squareMc.x = -getTopLeftOffset(squareMc).x;
            squareMc.y = -getTopLeftOffset(squareMc).y;
        }

        // return top left offset
        public function getTopLeftOffset(target : DisplayObject) : Point
        {
            return target.getBounds(target).topLeft
        }
    }
}