Selecting objects on a 2D map

Posted by Dave on Game Development See other posts from Game Development or by Dave
Published on 2012-03-20T21:23:10Z Indexed on 2012/03/21 5:40 UTC
Read the original article Hit count: 164

Filed under:

I have a object selection function by checking the mouse click and getting the relevant object.

How ever there is a rare situation where if one object is partially behind the other then both objects are in the given area so im wondering how I can make the game know which one was selected, as currently my method does not know.

This is my function that works it out:

function getobj(e){
    mx = e.pageX - curleft; //mouse click x
    my = e.pageY - curtop; //mouse click y

    function searchSprites(sprites, x, y) {
        var matches = [],
        i = 0,
        data = null;
        for (i = 0; i < spritea.length; ++i) {
            data = spritea[i].data;
            if (x > data[0] && y > data[1] && x < data[2] && y < data[3]) {     
                var imageData = ctx2.getImageData(x, y, 1, 1);
                if(imageData.data[3] !== 0){
                    return [spritea[i].id];
                    i = spritea.length;     
                }
            }
        }
    }
    res = searchSprites(spritea, mx, my);
    bid = res[0];
    if(bid === '1'){
        alert('You selected the skyscraper in front!');
    }else if(bid === '3'){
        alert('You selected the skyscraper behind!');
    }
}

Image of the map:

enter image description here

It keeps telling me I clicked the skyscraper behind which is not necessarily what the user is trying to do. How can I improve the accuracy of this ?

© Game Development or respective owner

Related posts about JavaScript