我正在用 html5 canvas 制作游戏。我正在使用 jquery,所以我可以获得点击事件和点击 x、y 坐标。我有一个单位对象数组和一个平铺地形(也是一个数组)。单元对象具有边界框信息、它们的位置和它们的类型。
将此点击事件映射到其中一个单元的最有效方法是什么?
最佳答案
循环遍历单元对象并确定哪个被点击,如下所示:
// '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`
请注意,这不会处理复杂的相交对象或 z-index 问题等...只是一个真正的起点。
关于javascript - 确定在 html5 canvas javascript 中点击了屏幕上的哪个对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3690748/