Not sure this exist, but worth asking you all: is there a built in method to compute the distance between the current mouse position and a given compone开发者_StackOverflownt? If not, is there a simple way to build a function like this that works for components with generic shapes?
thank you!
Okay, say you want the distance from the mouse to the top left corner (the default for Flex in this case), just use Pythagoras' theorem:
var d:int = Math.sqrt(Math.pow(theComponent.mouseX, 2) + Math.pow(theComponent.mouseY, 2));
Again, this would be the distance from the top left corner of 'theComponent'. If you want it to be from the center of the component, do this:
var d:int = Math.sqrt(Math.pow(theComponent.mouseX - theComponent.width/2, 2) + Math.pow(theComponent.mouseY - theComponent.height/2, 2));
Every DisplayObject has this 'mouseX/Y' property which is always relative to the top left corner.
Think I've got a solution put together for ya, I don't believe there's anything built in that'll do this for you outright though there may be a better way than this... but basically any solution I can think of basically uses the same concept so here it is:
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 is just a Label the handlers are just set on the application for this example but basically the only part that's important is the distance function given for operating on points and the localToGlobal call to convert the x/y position of the DisplayObject to absolute coordinates for comparison with the mouse position (to note you might need to use event.stageX, event.stageY in the move handler depending on what object you have handling that, I'm not sure that mouseX,mouseY are global coordinates). Also as noted in the comment this one is only going to take into account the top left corner of the shape not necessarily the closest edge for that you'll probably need to do some shape specific math unless someone has a more novel way.
精彩评论