views:

36

answers:

1

I'm making a game in html5 canvas. I'm using jquery so I can get the click event and the clicks x,y coordinates. I have an array of unit objects and a tiled terrain (also an array). The unit objects have bounding box information, their position, and their type.

What is the most effecient way to map this click event to one of the units?

+1  A: 

Loop through the unit objects and determine which was clicked like so:

// 'e' is the DOM event object
// 'c' is the canvas element
// 'units' is the array of unit objects
// (assuming each unit has x/y/width/height props)

var y = e.pageY,
    x = e.pageX,
    cOffset = $(c).offset(),
    clickedUnit;

// Adjust x/y values so we get click position relative to canvas element
x = x - cOffset.top;
y = y - cOffset.left;
// Note, if the canvas element has borders/outlines/margins then you
// will need to take these into account too.

for (var i = -1, l = units.length, unit; ++i < l;) {
    unit = units[i];
    if (
        y > unit.y && y < unit.y + unit.height &&
        x > unit.x && x < unit.x + unit.width
    ) {
        // Escape upon finding first matching unit
        clickedUnit = unit;
        break;
    }
}

// Do something with `clickedUnit`

Note, this won't handle complex intersecting objects or z-index issues etc... just a starting point really.

J-P