我创建了一个包含多个图像的图层。通过拖放,您可以在画布周围移动图像。在“dragend”事件中,我想检查实际图像是否位于任何其他图像上。
我将所有Kinetic.Image对象推入一个数组:形状。
function start() {
for (var i = 0; i < imgs.length; i++) {
var img = new Kinetic.Image({
x: i * 75 + 15,
y: i * 75 + 15,
width: 60,
height: 60,
image: imgs[i],
id: "img" + i,
draggable: true
});
layer.add(img);
img.on('dragend', function(e) {
var shape = e.targetNode;
doObjectsCollide(shape);
});
shapes.push(img);
}
layer.draw();
}
我找到了SO Question,它描述了两个元素之间碰撞的检测。我为我的情况尝试了解决方案,但在拖动结束后,没有检测到碰撞:
doObjectsCollide = function(a) {
for (var i = 0; i < shapes.length; i++) {
b = shapes[i];
if (a.id != b.id) {
if (
((a.getY() + a.getHeight()) < (b.getY())) ||
(a.getY() > (b.y + b.getHeight())) ||
((a.getX() + a.getWidth()) < b.getX()) ||
(a.getX() > (b.getX() + b.getWidth()))
) { console.log("Detection")};
}
}
}
循环有问题吗?或者形状是图像的事实?
答案 0 :(得分:1)
一些小故障:
将ids作为函数调用:if(a.id()!= b.id())
您的碰撞测试必须是不合理的:if(!(...))
所以doObjectsCollide应如下所示:
doObjectsCollide = function(a) {
for (var i = 0; i < shapes.length; i++) {
b = shapes[i];
if (a.id() != b.id()) {
if (
!(((a.getY() + a.getHeight()) < (b.getY())) ||
(a.getY() > (b.y + b.getHeight())) ||
((a.getX() + a.getWidth()) < b.getX()) ||
(a.getX() > (b.getX() + b.getWidth())))
) { console.log("Detection: "+a.id()+" hit "+b.id())};
}
}
}
这是一个演示:http://jsfiddle.net/m1erickson/PFH55/
干杯!