sumisu
sumisu

Reputation: 135

KineticJS - Detect Collisions of multiple images

I create a layer with multiple images. With drag and drop, you can move a image around the canvas. At the event "dragend", I want to check whether the actual image is located on any other image.

I push all Kinetic.Image Objects in an array: shapes.

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();

}

I found a SO Question which describes the detection of a collision between two elements. I try the solution for my case, but after the drag ends, no collision is detected:

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")};
    }
  }
}

Is there a problem with the loop? Or the fact that the shapes are images?

Upvotes: 0

Views: 199

Answers (1)

markE
markE

Reputation: 105015

A couple of glitches:

  • get ids as function calls: if( a.id() != b.id() )

  • your collision test must be not-ted: if( !(...) )

So doObjectsCollide should look like this:

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())};
    }
  }
}

Here's a Demo: http://jsfiddle.net/m1erickson/PFH55/

Cheers!

Upvotes: 1

Related Questions