find closest point to mouse position

血红的双手。 提交于 2019-12-12 01:59:34

问题


I've got a grid of sprites. Now I would like to drag an image on a grid-element. Therefore I need to know which x/y of the grid-element is the closest point to the mouse-position. All the grid-elements are stored in an array. How can I achieve that?


回答1:


If all you need is the x,y of the closest grid then all you have to do is.

var gridX:int = Math.floor(mouseX / NumberOfColumns);
var gridY:int = Math.floor(mouseY / NumberOfRows);

This will convert your mouse coordinates to your grid coordinates.

Now comes the problem. If your storing them in a 2d array then you have your x/y if your storing them in a flat array (1d) you need to look it up just like you created it.

var myObject:Object = my2dArray[gridX, gridY];
var myObject:Object = myFlatArray[(gridX * NumberOfRows) + gridY];

If you have taken care of how you create your array and push the items in it, it should be no problem to retrieve stuff without searching it.




回答2:


You must loop through all the elements and find the smallest distance to the mouse. Then store the array index of the element. Try something like this:

// Setup variables outside of loop.
var mousePoint:Point = new Point(mouseX, mouseY);
var elementPoint:Point = new Point();
var element:Sprite;
var closestIndex:uint = 0;
var closestDist:Number;

// Loop through elements
for (var i:int = 0; i < gridElements.length; i++) 
{
    element = gridElements[i] as Sprite;

    // Set the elementPoint's x and y rather than creating a new Point object.
    elementPoint.x = element.x;
    elementPoint.y = element.y;

    // Find distance from mouse to element.
    var dist:Number = Point.distance(mousePoint, elementPoint);

    // Update closestIndex and closestDist if it's the closest.
    if (i == 0 || dist < closestDist) 
    {
        closestDist = dist;
        closestIndex = i;
    }
}

// Can now use closestIndex to get the element from the array.
trace('The closest element is at index', closestIndex, ', with a distance of', closestDist);

Of course, this will only get you the first closest element, so you must decide what you want to happen if there are two elements an equal distance away.

You will also need to allow for the origins of your elements. The will probably have there origins set to there top left, so you need to allow for this in your distance calculation.

You could also check for a minimum distance. So if the user is dragging too far away from any of the elements then do nothing.



来源:https://stackoverflow.com/questions/6170392/find-closest-point-to-mouse-position

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