Question

I have a set of boxes in a board of 15x15.

I have only one eventlistener that catch a Touch Event and once a user tap on the screen, I need to know what box is nearest to such coordinate (x, y) given by the Event.

What could be the better way to get it?

Thanks in advance.

Was it helpful?

Solution

Simply take the difference of x & y positions & square them. Take the minimum d of all.

dx = x1 - x2;
dy = y1 - y2;
d = dx^2 + dy^2;

The two x & y would be of the box & the current touch point (Use .localX & .localY properties).

Here is a sample code, which probably has all you need :

board.addEventListener(TouchEvent.TOUCH_TAP,function(e) {

    var minVal:int = int.MAX_VALUE;     
    var minBox:Sprite = null;

    for(var i=0; i<board.numChildren; i++) {
        var box:Sprite = board.getChildAt(i);
        var d:int = Math.pow(box.x-e.localX ,2) + Math.pow(box.y-e.localY,2);  
        if(minVal > d) {minVal = d; minBox = box; }
    }

    // You have the minimum value & closest box reference here

});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top