문제

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.

도움이 되었습니까?

해결책

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

});
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top