2011-03-28 123 views
0

不确定这是否存在,但值得问问大家:是否有内置方法来计算当前鼠标位置和给定组件之间的距离?如果没有,是否有一种简单的方法来构建这样的函数,它适用于具有通用形状的组件?鼠标和组件之间的距离

谢谢!

+0

你正在寻找这个距离到形状上的最近点或形状的中心? – 2011-03-28 23:33:35

+0

理想情况下距离形状上的最近点 - 但我意识到这可能太难通用形状的问题。我会采取合理的近似。 – 2011-03-29 00:25:42

+0

我可以问你想用这个完成什么吗? – 2011-03-29 02:29:46

回答

1

好吧,假设你想从鼠标到左上角(在这种情况下,默认的Flex)的距离,只要使用毕达哥拉斯定理:

var d:int = Math.sqrt(Math.pow(theComponent.mouseX, 2) + Math.pow(theComponent.mouseY, 2)); 

同样,这将是从距离'theComponent'的左上角。如果你希望它是从部件的中心,这样做:

var d:int = Math.sqrt(Math.pow(theComponent.mouseX - theComponent.width/2, 2) + Math.pow(theComponent.mouseY - theComponent.height/2, 2)); 

每个DisplayObject有这个“mouseX/Y”属性,它始终是相对于左上角。

+0

感谢您对mouseX的澄清,mouseY @J_A_X我找不到记录在任何地方,应该只是做了一些更多的测试,我想。 – shaunhusain 2011-03-29 15:16:50

+0

您是否尝试过Adobe API?一切都在那里...... http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/ – 2011-03-29 15:31:47

+0

Yah通常我发现文档是好的,但在这种情况下,没有明确描述事实mouseX将相对于组件,而不是阶段或组件容器或其他东西...只提及有关旋转,但没有更多http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash /display/DisplayObject.html#mouseX – shaunhusain 2011-03-29 15:38:32

1

想想我有一个解决方案放在一起为雅,我不相信有什么内置的,这将为你彻底做到这一点,虽然有可能比这更好的方式......但基本上任何解决方案我能想到的基本上都采用相同的概念所以在这里,它是:

private var lastClickedComponent:DisplayObject; 
    private var lastClickedGlobalPos:Point; 

    protected function application1_clickHandler(event:MouseEvent):void 
    { 
     // TODO Auto-generated method stub 
     lastClickedComponent = event.target as DisplayObject; 
     if(lastClickedComponent) 
      lastClickedGlobalPos = lastClickedComponent.parent.localToGlobal(new Point(lastClickedComponent.x,lastClickedComponent.y)); 
    } 

    private function distanceToLastClicked():void 
    { 
     if(lastClickedComponent) 
     { 
      distanceLabel.text = Point.distance(lastClickedGlobalPos,new Point(mouseX,mouseY)).toString(); 
     } 
    } 


    protected function application1_mouseMoveHandler(event:MouseEvent):void 
    { 
     distanceToLastClicked(); 
    } 

distanceLabel仅仅是一个标签的处理程序只设置在这个例子中的应用程序,但基本上这是唯一重要的部分是用于操作给出的距离函数on point和localToGlobal调用将DisplayObject的x/y位置转换为绝对坐标以与鼠标位置进行比较(注意,您可能需要在移动手柄中使用event.stageX,event.stageY呃取决于你要处理的对象,我不确定那个mouseX,mouseY是全局坐标)。同样正如评论中指出的那样,这只是考虑到形状的左上角不一定是最接近的边缘,否则你可能需要做一些形状特定的数学计算,除非有更新颖的方法。