开发者

Identify which object on screen clicked in html5 canvas javascript?

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?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜